Deep file and folder/directory copy in .NET
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);
}
}