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

29,928

Solution 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);
    }
}

Solution 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.

Solution 3

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

Share:
29,928
dthrasher
Author by

dthrasher

Senior Solution Architect at EPAM Systems, specializing in Microsoft.NET and Sitecore. Former co-founder of Infovark, Inc.

Updated on December 30, 2020

Comments

  • dthrasher
    dthrasher over 3 years

    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.