溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C#中怎么拷貝整個文件夾及子目錄

發(fā)布時間:2021-06-16 14:54:21 來源:億速云 閱讀:161 作者:Leah 欄目:編程語言

本篇文章給大家分享的是有關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# 拷貝指定文件夾下的所有文件及其文件夾到指定目錄

要拷貝的文件及其文件夾結構

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#中怎么拷貝整個文件夾及子目錄,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)
推薦閱讀:
  1. C# 深拷貝
  2. C# 淺拷貝

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI