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

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

问题描述:

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

What is the best way to recursively copy a folder's content into another folder using C# and ASP.NET?

你可以试试这个

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

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

and this is the method that do all the work:

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

我希望这会有所帮助:)

I hope this will help :)