2011-08-22 57 views
41

Làm thế nào tôi có thể sao chép tất cả nội dung trong một thư mục này sang thư mục khác với vòng lặp lặp lại trên mỗi tệp?Sao chép tất cả các tập tin trong thư mục

+0

Xem tại đây: http://stackoverflow.com/questions/206323/how-to-execute-command-line-in-c-get-std-out-results và đặt ở đó cho lệnh "sao chép \ *. * YOURDIR " – fritzone

Trả lời

1

Bạn không thể. Nhưng bạn có thể sử dụng một số loại mã ngắn gọn như Directory.GetFiles(mydir).ToList().ForEach(f => File.Copy(f, otherdir + "\\" f);

+3

Điều này không hoạt động đệ quy. –

78

Bạn không thể. Không phải là Directory cũng không phải DirectoryInfo cung cấp phương thức Copy. Bạn cần phải thực hiện điều này cho mình.

void Copy(string sourceDir, string targetDir) 
{ 
    Directory.CreateDirectory(targetDir); 

    foreach(var file in Directory.GetFiles(sourceDir)) 
     File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file))); 

    foreach(var directory in Directory.GetDirectories(sourceDir)) 
     Copy(directory, Path.Combine(targetDir, Path.GetFileName(directory))); 
} 

Vui lòng đọc nhận xét để biết một số vấn đề với phương pháp đơn giản này.

+0

Điều này chỉ sao chép tệp, nó không tạo bất kỳ thư mục con nào. Vì vậy, nếu đích đến chưa có cấu trúc thư mục giống nhau, bạn sẽ cần phải thêm một dòng ở đầu để tạo đích nếu nó chưa tồn tại. – Ross

+1

@Ross: Thật vậy, đã sửa. Xin lưu ý rằng điều này không sao chép các thuộc tính bảo mật như quyền truy cập. –

+1

bằng cách kiểm tra xem tệp và thư mục có tồn tại hay không. if (! Directory.Exists (targetDir)) ... if (! File.Exists (file)) – Misi

0

Execute xcopy source_directory\*.* destination_directory như một lệnh bên ngoài. Tất nhiên điều này sẽ chỉ hoạt động trên các máy Windows.

+0

Bạn không nên sử dụng các cuộc gọi hệ thống nếu không cần thiết. Ở đây, nó chắc chắn là không cần thiết. –

+0

Điều cần thiết là câu hỏi nêu rõ ** với vòng lặp lặp lại mỗi tệp **. – m0skit0

+0

Và bạn nghĩ gì về xcopy? Anh ta không muốn lặp lại, bởi vì anh ta nghĩ có một cách dễ dàng hơn. Không có. Và một cuộc gọi hệ thống không phải là dễ dàng hơn cũng không phải là một cách tốt nói chung. Nó được khuyến khích mạnh mẽ! –

8

Bạn có thể sử dụng phương pháp FileSystem.CopyDirectory VB để đơn giản hóa các nhiệm vụ:

using Microsoft.VisualBasic.FileIO; 

foo(){ 
    FileSystem.CopyDirectory(directoryPath, tempPath); 
} 
+2

Tôi nhớ VB. Và mọi người nói bạn có thể làm tất cả những điều tương tự trong C#. –

-1
Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + @"resources\html") 
    .ToList() 
    .ForEach(f => File.Copy(f, folder + "\\" + f.Substring(f.LastIndexOf("\\")))); 
2
using System.IO; 

string sourcePath = @"D:\test"; 
string targetPath = @"D:\test_new"; 
if (!Directory.Exists(targetPath)) 
{ 
    Directory.CreateDirectory(targetPath); 
} 
foreach (var srcPath in Directory.GetFiles(sourcePath)) 
{ 
    //Copy the file from sourcepath and place into mentioned target path, 
    //Overwrite the file if same file is exist in target path 
    File.Copy(srcPath, srcPath.Replace(sourcePath, targetPath), true); 
} 
0

này hoạt động tuyệt vời! Nó sẽ sao chép các thư mục con hoặc bạn chỉ có thể đổ tất cả các tệp từ tất cả các thư mục con vào một vị trí.

/// AUTHOR : Norm Petroff 
/// <summary> 
/// Takes the files from the PathFrom and copies them to the PathTo. 
/// </summary> 
/// <param name="pathFrom"></param> 
/// <param name="pathTo"></param> 
/// <param name="filesOnly">Copies all files from each directory to the "PathTo" and removes directory.</param> 
static void CopyFiles(String pathFrom, String pathTo, Boolean filesOnly) 
{ 
    foreach(String file in Directory.GetFiles(pathFrom)) 
    { 
     // Copy the current file to the new path. 
     File.Copy(file, Path.Combine(pathTo, Path.GetFileName(file)), true); 

     // Get all the directories in the current path. 
     foreach (String directory in Directory.GetDirectories(pathFrom)) 
     { 
      // If files only is true then recursively get all the files. They will be all put in the original "PathTo" location 
      // without the directories they were in. 
      if (filesOnly) 
      { 
       // Get the files from the current directory in the loop. 
       CopyFiles(directory, pathTo, filesOnly); 
      } 
      else 
      { 
       // Create a new path for the current directory in the new location.      
       var newDirectory = Path.Combine(pathTo, new DirectoryInfo(directory).Name); 

       // Copy the directory over to the new path location if it does not already exist. 
       if (!Directory.Exists(newDirectory)) 
       { 
        Directory.CreateDirectory(newDirectory); 
       } 

       // Call this routine again with the new path. 
       CopyFiles(directory, newDirectory, filesOnly); 
      } 
     } 
    } 
} 
Các vấn đề liên quan