Krystalware
Products | Purchase | Free Stuff | Forums | Blog | Testimonials | Company | Contact

I just ran up against a requirement to do a deep file and folder/directory copy in .NET (C# to be exact). A quick google didn't turn up any code, so I figured I'd post what I came up with. This is a somewhat naive implementation that may run out of steam for very deep folders or 1000s of files, but works great for most things. This implementation takes a source folder and a destination folder and copies the entire structure including files and folders from the source folder to the destination.

So without further ado:

private void CopyFolder(string folder, string destFolder)
{
  Directory.CreateDirectory(destFolder);

  foreach (string file in Directory.GetFiles(folder, "*.*", SearchOption.AllDirectories))
  {
    string fileName = Path.GetFileName(file);
    string filePath = Path.GetDirectoryName(file.Substring(folder.Length + 1));
    string destFilePath;

    if (!string.IsNullOrEmpty(filePath))
    {
      string destFolder = Path.Combine(destFolder, filePath);

      Directory.CreateDirectory(destFolder);

      destFilePath = Path.Combine(destFolder, fileName);
    }
    else
    {
      destFilePath = Path.Combine(destFolder, fileName);
    }        

    File.Copy(file, destFilePath);
  }
}
posted on Monday, January 28, 2008 2:24 PM | Filed Under [ ASP.NET Client Code ]

Comments

Gravatar
# re: Deep file and folder/directory copy in .NET
Posted by Bill Pierce
on 1/29/2008 9:36 AM
Any reason why you wouldn't launch a RoboCopy process? Or an XCopy process? Tried and true, probably faster with no 'unknown' deep copy issues.

-Bill
Gravatar
# re: Deep file and folder/directory copy in .NET
Posted by Chris Hynes
on 1/29/2008 10:14 AM
That's certainly a valid approach. Personally, I typically try to stay in .NET unless there's a clear reason to use external processes. Shelling out to robocopy or xcopy means possible additional dependancies, permissions issues, etc. If perf becomes a problem, that's definitely the next step. Right now, though, perf seems great, and the solution using it has unit tests for its functionality as well as performance.
Title  
Name
Email (never displayed)
Url
Comments   
Please add 4 and 1 and type the answer here: