To copy all files from one directory to another while preserving the directory structure, you can use a recursive approach that walks through each subdirectory and recreates the same structure in the destination.
Here’s a complete example in C#:
Recursive Directory Copy (Preserving Structure)
using System;
using System.IO;
public class DirectoryCopier
{
public static void CopyDirectory(string sourceDir, string destDir)
{
// Create the destination directory if it doesn't exist
Directory.CreateDirectory(destDir);
// Copy all files in the current directory
foreach (var filePath in Directory.GetFiles(sourceDir))
{
string fileName = Path.GetFileName(filePath);
string destFilePath = Path.Combine(destDir, fileName);
File.Copy(filePath, destFilePath, overwrite: true);
}
// Recurse into subdirectories
foreach (var subDir in Directory.GetDirectories(sourceDir))
{
string subDirName = Path.GetFileName(subDir);
string newDestSubDir = Path.Combine(destDir, subDirName);
CopyDirectory(subDir, newDestSubDir);
}
}
}
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To copy all files from one directory to another while preserving the directory structure, you can use a recursive approach that walks through each subdirectory and recreates the same structure in the destination.
Here’s a complete example in C#:
Recursive Directory Copy (Preserving Structure)
Example Usage
Notes
overwrite: true).