温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#怎么拷贝整个文件夹及子目录和其中文件

发布时间:2021-08-25 17:35:50 来源:亿速云 阅读:132 作者:chen 栏目:编程语言

这篇文章主要讲解了“C#怎么拷贝整个文件夹及子目录和其中文件”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C#怎么拷贝整个文件夹及子目录和其中文件”吧!

下面一段代码给大家介绍C#拷贝整个文件夹以及子目录和其中文件,具体代码如下所示:

private void CopyDirectory( string srcPath, string desPath)   {    string folderName = srcdir.Substring(srcdir.LastIndexOf( "\\" )+1);    string desfolderdir = desPath + "\\" + folderName;    if (desdir.LastIndexOf( "\\" ) == (desPath.Length - 1))    {     desfolderdir = desPath + folderName;    }    string [] filenames = Directory.GetFileSystemEntries(srcPath);    foreach ( string file in filenames)     {     if (Directory.Exists(file))      {      string currentdir = desfolderdir + "\\" + file.Substring(file.LastIndexOf( "\\" ) + 1);      if (!Directory.Exists(currentdir))      {       Directory.CreateDirectory(currentdir);      }      CopyDirectory(file, desfolderdir);     }     else      {      string srcfileName = file.Substring(file.LastIndexOf( "\\" )+1);      srcfileName = desfolderdir + "\\" + srcfileName;      if (!Directory.Exists(desfolderdir))      {       Directory.CreateDirectory(desfolderdir);      }           File.Copy(file, srcfileName);     }    }    }

ps:C# 拷贝指定文件夹下的所有文件及其文件夹到指定目录

要拷贝的文件及其文件夹结构

其中.lab文件不能覆盖

/// <summary>/// 拷贝oldlab的文件到newlab下面/// </summary>/// <param name="sourcePath">lab文件所在目录(@"~\labs\oldlab")</param>/// <param name="savePath">保存的目标目录(@"~\labs\newlab")</param>/// <returns>返回:true-拷贝成功;false:拷贝失败</returns>public bool CopyOldLabFilesToNewLab(string sourcePath, string savePath){  if (!Directory.Exists(savePath))  {    Directory.CreateDirectory(savePath);  }  #region //拷贝labs文件夹到savePath下  try  {    string[] labDirs = Directory.GetDirectories(sourcePath);//目录    string[] labFiles = Directory.GetFiles(sourcePath);//文件    if (labFiles.Length > 0)    {      for (int i = 0; i < labFiles.Length; i++)      {        if (Path.GetExtension(labFiles[i]) != ".lab")//排除.lab文件        {          File.Copy(sourcePath + "\\" + Path.GetFileName(labFiles[i]), savePath + "\\" + Path.GetFileName(labFiles[i]), true);        }      }    }    if (labDirs.Length > 0)    {      for (int j = 0; j < labDirs.Length; j++)      {        Directory.GetDirectories(sourcePath + "\\" + Path.GetFileName(labDirs[j]));        //递归调用        CopyOldLabFilesToNewLab(sourcePath + "\\" + Path.GetFileName(labDirs[j]), savePath + "\\" + Path.GetFileName(labDirs[j]));      }    }  }  catch (Exception)  {    return false;  }  #endregion  return true;}

感谢各位的阅读,以上就是“C#怎么拷贝整个文件夹及子目录和其中文件”的内容了,经过本文的学习后,相信大家对C#怎么拷贝整个文件夹及子目录和其中文件这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI