How do I copy a folder and all subfolders and files in .NET? [duplicate]

隐身守侯 提交于 2019-12-17 21:58:09

问题


Possible Duplicate:
Best way to copy the entire contents of a directory in C#

I'd like to copy folder with all its subfolders and file from one location to another in .NET. What's the best way to do this?

I see the Copy method on the System.IO.File class, but was wondering whether there was an easier, better, or faster way than to crawl the directory tree.


回答1:


Well, there's the VisualBasic.dll implementation that Steve references, and here's something that I've used.

private static void CopyDirectory(string sourcePath, string destPath)
{
    if (!Directory.Exists(destPath))
    {
        Directory.CreateDirectory(destPath);
    }

    foreach (string file in Directory.GetFiles(sourcePath))
    {
        string dest = Path.Combine(destPath, Path.GetFileName(file));
        File.Copy(file, dest);
    }

    foreach (string folder in Directory.GetDirectories(sourcePath))
    {
        string dest = Path.Combine(destPath, Path.GetFileName(folder));
        CopyDirectory(folder, dest);
    }
}



回答2:


Michal Talaga references the following in his post:

  • Microsoft's explanation about why there shouldn't be a Directory.Copy() operation in .NET.
  • An implementation of CopyDirectory() from the Microsoft.VisualBasic.dll assembly.

However, a recursive implementation based on File.Copy() and Directory.CreateDirectory() should suffice for the most basic of needs.




回答3:


If you don't get anything better... perhaps use Process.Start to fire up robocopy.exe?



来源:https://stackoverflow.com/questions/1066674/how-do-i-copy-a-folder-and-all-subfolders-and-files-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!