Deep file and folder/directory copy in .NET
January 28. 2008 5 Comments
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 + (folder.EndsWith("\\") ? 0 : 1)));
string destFilePath;
if (!string.IsNullOrEmpty(filePath))
{
string destFolderPath = Path.Combine(destFolder, filePath);
Directory.CreateDirectory(destFolderPath);
destFilePath = Path.Combine(destFolderPath, fileName);
}
else
{
destFilePath = Path.Combine(destFolder, fileName);
}
File.Copy(file, destFilePath);
}
}
Comments
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 Pierce-Bill
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.
Chris HynesGood work...
tervelbut it won't work :)
You have a local variable called destFolder, same as [another] local variable that is the second param to the method. As a result the code won't compile
Good catch. Damn copy/paste. Fixed...
programcsharpIt dies when it hits "System Volume Information". You need to add code to handle exceptions like improper permissions issues.
Notstarman