如何在 .NET 中复制文件夹以及所有子文件夹和文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1066674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I copy a folder and all subfolders and files in .NET?
提问by dthrasher
Possible Duplicate:
Best way to copy the entire contents of a directory in C#
可能的重复:
在 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?
我想将文件夹及其所有子文件夹和文件从一个位置复制到 .NET 中的另一个位置。做到这一点的最佳方法是什么?
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.
我在 System.IO.File 类上看到了 Copy 方法,但想知道是否有比爬行目录树更简单、更好或更快的方法。
回答by Michael Petrotta
Well, there's the VisualBasic.dll implementation that Steve references, and here's something that I've used.
嗯,有 Steve 引用的 VisualBasic.dll 实现,这里有一些我使用过的东西。
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);
}
}
回答by Steve Guidi
Michal Talaga references the following in his post:
Michal Talaga 在他的帖子中引用了以下内容:
- 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.
- Microsoft 关于为什么在 .NET 中不应该有 Directory.Copy() 操作的解释。
- Microsoft.VisualBasic.dll 程序集中的 CopyDirectory() 实现。
However, a recursive implementation based on File.Copy()and Directory.CreateDirectory()should suffice for the most basic of needs.
但是,基于File.Copy()并且Directory.CreateDirectory()应该满足最基本需求的递归实现。
回答by Marc Gravell
If you don't get anything better... perhaps use Process.Startto fire up robocopy.exe?
如果你没有得到更好的东西......也许Process.Start用来激发robocopy.exe?

