views:

1113

answers:

3

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  A: 

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

Marc Gravell
+10  A: 

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.

Steve Guidi
That's an interesting link. I'm not sure Microsoft's arguments hold much water. But it does explain why the functionality is missing.
dthrasher
+7  A: 

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);
    }
}
Michael Petrotta