在C#中递归复制内容的最佳方法是什么?

时间:2009-03-09 18:38:20

标签: c# asp.net recursion

使用C#和ASP.NET以递归方式将文件夹的内容复制到另一个文件夹的最佳方法是什么?

3 个答案:

答案 0 :(得分:34)

你可以试试这个

DirectoryInfo sourcedinfo = new DirectoryInfo(@"E:\source");
DirectoryInfo destinfo = new DirectoryInfo(@"E:\destination");
copy.CopyAll(sourcedinfo, destinfo);

这是完成所有工作的方法:

public void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
    try
    {
        //check if the target directory exists
        if (Directory.Exists(target.FullName) == false)
        {
            Directory.CreateDirectory(target.FullName);
        }

        //copy all the files into the new directory

        foreach (FileInfo fi in source.GetFiles())
        {
            fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
        }


        //copy all the sub directories using recursion

        foreach (DirectoryInfo diSourceDir in source.GetDirectories())
        {
            DirectoryInfo nextTargetDir = target.CreateSubdirectory(diSourceDir.Name);
            CopyAll(diSourceDir, nextTargetDir);
        }
        //success here
    }
    catch (IOException ie)
    {
        //handle it here
    }
}

我希望这会有所帮助:)

答案 1 :(得分:18)

只需在Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory程序集中使用Microsoft.VisualBasic.dll

添加对Microsoft.VisualBasic

的引用
Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(source, destination);

答案 2 :(得分:6)

您可以使用SearchOption.AllDirectories递归搜索文件夹,只需在复制之前创建目录...

// string source, destination; - folder paths 
int pathLen = source.Length + 1;

foreach (string dirPath in Directory.GetDirectories(source, "*", SearchOption.AllDirectories))
{
    string subPath = dirPath.Substring(pathLen);
    string newpath = Path.Combine(destination, subPath);
    Directory.CreateDirectory(newpath );
}

foreach (string filePath in Directory.GetFiles(source, "*.*", SearchOption.AllDirectories))
{
    string subPath = filePath.Substring(pathLen);
    string newpath = Path.Combine(destination, subPath);
    File.Copy(filePath, newpath);
}