栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

C#拷贝整个文件夹及子目录和其中文件的方法

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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文件不能覆盖

/// 
/// 拷贝oldlab的文件到newlab下面
/// 
/// lab文件所在目录(@"~labsoldlab")
/// 保存的目标目录(@"~labsnewlab")
/// 返回:true-拷贝成功;false:拷贝失败
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;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/122502.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号