如何创建递归函数来复制所有文件和文件夹

时间:2012-04-30 19:51:00

标签: c# .net winforms visual-studio-2010 recursion

我正在尝试创建一个函数,该函数将递归地将源文件夹及其中的所有文件和文件夹复制到其他位置。

目前,我必须在主文件夹中定义每个文件夹,这使得代码变得臃肿和冗余。

这样做更有效的方法是什么?

4 个答案:

答案 0 :(得分:10)

看看我的问题:

performance of copying directories 我使用了平行的foreach并且它非常快

private static void CopyAll(string SourcePath, string DestinationPath)
{

string[] directories = System.IO.Directory.GetDirectories(SourcePath, "*.*", SearchOption.AllDirectories);

Parallel.ForEach(directories, dirPath =>
{
    Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
}); 

string[] files = System.IO.Directory.GetFiles(SourcePath, "*.*", SearchOption.AllDirectories);

Parallel.ForEach(files, newPath =>
{
    File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath));
}); 
}

答案 1 :(得分:4)

来源:C# - Copy files and folders recursively from source to destination folder in c-sharp

public static void CopyFolder(string sourceFolder, string destFolder)  
{  
    if (!Directory.Exists(destFolder))  
        Directory.CreateDirectory(destFolder); 

    string[] files = Directory.GetFiles(sourceFolder);  
    foreach (string file in files)  
    {  
        string name = Path.GetFileName(file);  
        string dest = Path.Combine(destFolder, name);  
        File.Copy(file, dest);  
    }  
    string[] folders = Directory.GetDirectories(sourceFolder);  
    foreach (string folder in folders)  
    {  
        string name = Path.GetFileName(folder);  
        string dest = Path.Combine(destFolder, name);  
        CopyFolder(folder, dest);  
    }  
}

答案 2 :(得分:2)

这样做

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

答案 3 :(得分:0)

在我看来,使用GetDirectories / GetFiles有点过时,我会使用Directory.EnumerateFileSystemEntries(source);,因为它更快。