2010-04-30 46 views
7

Tôi cần phải sao chép Thư mục từ một ổ đĩa sang Ổ cứng di động. Thư mục cần được sao chép sẽ có nhiều thư mục con và tệp trong đó. Đầu vào sẽ là Đường dẫn nguồn và Đường dẫn đích.Cách tốt nhất để sao chép thư mục và tất cả thư mục con và tệp bằng C#

Giống như ..

Nguồn Đường dẫn: "C: \ SourceFolder"

Target Path: "E: \"

Sau khi chép xong, tôi shud có thể nhìn thấy thư mục " SourceFolder "trong E của tôi: lái xe.

Cảm ơn.

+1

Đây là một bản sao, xem : http://stackoverflow.com/questions/58744/best-way-to-copy-the-entire-contents-of-a-directory-in-c – Ash

+0

Một quảng cáo song hành khác licate: http://stackoverflow.com/questions/627504/what-is-the-best-way-to-recursively-copy-contents-in-c – Ash

+0

Hm, giờ đây mọi người chỉ sao chép từ các câu hỏi khác, vì vậy Tôi đang bỏ phiếu để đóng. –

Trả lời

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

Danh bạ nào.CreateDirectory (DI_Target + "// Database"); là –

3

Làm thế nào để: sao chép, xóa, và Move Files and Folders (C# Programming Guide)
http://msdn.microsoft.com/en-us/library/cc148994.aspx

Làm thế nào để: Lặp lại Qua một cây thư mục (C# Programming Guide)
http://msdn.microsoft.com/en-us/library/bb513869.aspx

+0

Chỉ cần fyi, Mã trên trang đó rời khỏi phần mà anh ấy thực sự cần. Lưu ý nhận xét, * Để đệ quy lặp qua tất cả các thư mục con trong thư mục hiện tại, hãy xem "Cách: Lặp qua cây thư mục." * – egrunin

+0

@egrunin: Cảm ơn. –

8

Tìm thấy mục này tại Channel9. Đã không thử nó bản thân mình.

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); 
     } 
    } 
} 

và việc sử dụng trông như thế này:

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

+1 Phương pháp mở rộng tốt đẹp. –

-1

Tại sao không bạn sử dụng một cái gì đó giống như Robocopy?

Tùy chọn phản chiếu trong đó cấu trúc thư mục của nguồn được sao chép dưới dạng là điểm đến không chính xác. Có nhiều tùy chọn dòng lệnh khác nhau. Có thể giúp bạn tiết kiệm nỗ lực để nhân rộng các tính năng trong mã của bạn.

+1

Bởi vì RoboCopy là một ứng dụng bên ngoài. Nó luôn luôn tốt hơn để thử làm những điều tự nhiên trong mã đầu tiên (nếu nó không phải là quá phức tạp để làm như vậy), trước khi nghỉ để bắn phá ra một chương trình khác để làm chúng. –

11

Tôi nghĩ rằng đây là nó.

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

Có vấn đề về quyền. Bạn có thể vượt qua nó? –

-1

Và đây là một mất khác nhau về vấn đề này:

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

cho nhân viên của Google: trong win32 thuần túy/C++, sử dụng 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

Không phải là câu hỏi này về C#? Không phải là tôi phàn nàn (vẫn còn upvoted). Phương pháp rất hữu ích, jsut một chút trong bối cảnh ở đây –

Các vấn đề liên quan