30

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.

Community
  • 1
  • 1
dthrasher
  • 40,656
  • 34
  • 113
  • 139
  • http://xneuron.wordpress.com/2007/04/12/copy-directory-and-its-content-to-another-directory-in-c/ might be helpful to you; it shows a simple recursive method – Daniel LeCheminant Jul 01 '09 at 00:03
  • 1
    I look forward to when I need to do operations on the file system because I have a legitimate excuse to use recursion! – mmcdole Jul 01 '09 at 00:46

3 Answers3

51

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
  • 59,888
  • 27
  • 145
  • 179
12

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
  • 19,700
  • 9
  • 74
  • 90
  • 1
    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 Jul 01 '09 at 14:45
3

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

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Robocopy doesn't parse quotes properly when run with Process.Start, so your source/destination paths must not contain spaces. If they do, you have to use the 8dot3 filename. The only time Robocopy seems to accept quotes properly is from a command line or BAT file. – Brain2000 Dec 02 '11 at 12:35
  • @Brain2000 you can always use short paths if spaces are an issue – David Work Mar 30 '15 at 17:54