问题
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