当前位置: 移动技术网 > IT编程>开发语言>c# > C#拷贝整个文件夹及子目录和其中文件的方法

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

下面一段代码给大家介绍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;
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网