2010-04-30 71 views
7

我需要將文件夾從一個驅動器複製到可移動硬盤。 需要複製的文件夾中會包含許多子文件夾和文件。 輸入將是源路徑和目標路徑。什麼是使用c複製文件夾和所有子文件夾和文件的最佳方式#

如..

源路徑: 「C:\ SourceFolder」

目標路徑: 「E:\」

複製完成後,我shud能夠看到該文件夾​​「 SourceFolder「在我的E:驅動器中。

謝謝。

+1

這是一個重複,看: http://stackoverflow.com/questions/58744/best-way-to-copy-the-entire-contents-of-a-directory-in-c – Ash 2010-04-30 04:41:20

+0

另一個dup licate:http://stackoverflow.com/questions/627504/what-is-the-best-way-to-recursively-copy-contents-in-c – Ash 2010-04-30 04:54:36

+0

嗯,現在人們只是從其他問題複製,所以我正在投票結束。 – 2010-04-30 04:57:40

回答

2
private static bool CopyDirectory(string SourcePath, string DestinationPath, bool overwriteexisting) 
     { 
      bool ret = true; 
      try 
      { 
       SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\"; 
       DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\"; 

       if (Directory.Exists(SourcePath)) 
       { 
        if (Directory.Exists(DestinationPath) == false) 
         Directory.CreateDirectory(DestinationPath); 

        foreach (string fls in Directory.GetFiles(SourcePath)) 
        { 
         FileInfo flinfo = new FileInfo(fls); 
         flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting); 
        } 
        foreach (string drs in Directory.GetDirectories(SourcePath)) 
        { 
         DirectoryInfo drinfo = new DirectoryInfo(drs); 
         if (CopyDirectory(drs, DestinationPath + drinfo.Name, overwriteexisting) == false) 
          ret = false; 
        } 
        Directory.CreateDirectory(DI_Target + "//Database"); 
       } 
       else 
       { 
        ret = false; 
       } 
      } 
      catch (Exception ex) 
      { 
       ret = false; 
      } 
      return ret; 
     } 
+0

什麼目錄。CreateDirectory(DI_Target +「// Database」);是 – 2013-07-19 13:25:49

3

如何:複製,刪除,移動文件和文件夾(C#編程指南)
http://msdn.microsoft.com/en-us/library/cc148994.aspx

如何:迭代通過目錄樹(C#編程指南)
http://msdn.microsoft.com/en-us/library/bb513869.aspx

+0

只是fyi,該頁面上的代碼留下了他真正需要的部分。請注意註釋,*要遞歸遍歷當前目錄下的所有子文件夾,請參閱「如何:通過目錄樹迭代」。* – egrunin 2010-04-30 04:42:26

+0

@egrunin:謝謝。 – 2010-04-30 04:44:40

8

Channel9找到了。還沒有嘗試過自己。

public static class DirectoryInfoExtensions 
{ 
    // Copies all files from one directory to another. 
    public static void CopyTo(this DirectoryInfo source, 
      string destDirectory, bool recursive) 
    { 
     if (source == null) 
      throw new ArgumentNullException("source"); 
     if (destDirectory == null) 
      throw new ArgumentNullException("destDirectory"); 
     // If the source doesn't exist, we have to throw an exception. 
     if (!source.Exists) 
      throw new DirectoryNotFoundException(
        "Source directory not found: " + source.FullName); 
     // Compile the target. 
     DirectoryInfo target = new DirectoryInfo(destDirectory); 
     // If the target doesn't exist, we create it. 
     if (!target.Exists) 
      target.Create(); 
     // Get all files and copy them over. 
     foreach (FileInfo file in source.GetFiles()) 
     { 
      file.CopyTo(Path.Combine(target.FullName, file.Name), true); 
     } 
     // Return if no recursive call is required. 
     if (!recursive) 
      return; 
     // Do the same for all sub directories. 
     foreach (DirectoryInfo directory in source.GetDirectories()) 
     { 
      CopyTo(directory, 
       Path.Combine(target.FullName, directory.Name), recursive); 
     } 
    } 
} 

和用法如下:

var source = new DirectoryInfo(@"C:\users\chris\desktop"); 
source.CopyTo(@"C:\users\chris\desktop_backup", true); 
+0

+1漂亮的擴展方法。 – 2010-04-30 04:45:22

-1

你爲什麼不使用類似Robocopy

它有一個鏡像選項,其中源的目錄結構原樣複製到目的地。有各種命令行選項。可以節省您在代碼中複製功能的努力。

+1

因爲RoboCopy是一個外部應用程序。最好先嚐試在代碼中進行本地代碼處理(如果這樣做不是太複雜的話),然後再採取措施解決其他程序來執行它們。 – 2010-04-30 04:51:15

11

我認爲就是這樣。

public static void CopyFolder(DirectoryInfo source, DirectoryInfo target) { 
    foreach (DirectoryInfo dir in source.GetDirectories()) 
     CopyFolder(dir, target.CreateSubdirectory(dir.Name)); 
    foreach (FileInfo file in source.GetFiles()) 
     file.CopyTo(Path.Combine(target.FullName, file.Name)); 
} 
+0

它有權限問題。你能克服它嗎? – 2017-03-18 18:56:45

-1

這裏是一個不同的看法的問題:

System.Diagnostics.ProcessStartInfo psi = 
    new System.Diagnostics.ProcessStartInfo(@"XCOPY C:\folder D:\Backup\folder /i"); 
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; 
psi.UseShellExecute = false; 
System.Diagnostics.Process copyFolders = System.Diagnostics.Process.Start(psi); 
copyFolders.WaitForExit(); 
1

,讓Google:在純粹的Win32/C++中,使用SHCreateDirectoryEx

inline void EnsureDirExists(const std::wstring& fullDirPath) 
{ 
    HWND hwnd = NULL; 
    const SECURITY_ATTRIBUTES *psa = NULL; 
    int retval = SHCreateDirectoryEx(hwnd, fullDirPath.c_str(), psa); 
    if (retval == ERROR_SUCCESS || retval == ERROR_FILE_EXISTS || retval == ERROR_ALREADY_EXISTS) 
     return; //success 

    throw boost::str(boost::wformat(L"Error accessing directory path: %1%; win32 error code: %2%") 
     % fullDirPath 
     % boost::lexical_cast<std::wstring>(retval)); 

    //TODO *djg* must do error handling here, this can fail for permissions and that sort of thing 
} 
+1

不是關於C#的這個問題嗎?並不是說我在抱怨(仍然是upvoted)。非常有用的方法,在這裏稍微超出上下文 – 2015-02-11 16:19:40

相關問題