Hello Devz,
It’s unbelievable but yes, the System.IO provided by .NET doesn’t have a simple method to copy a folder, its content and the sub directories to another destination.
There are a few different techniques to copy a directory with C#, using the command XCopy, or using a recursive method.
The best one I saw was the one from MSDN:
class Program { static void Main(string[] args) { string sourceDirectory = @"C:\temp\source"; string targetDirectory = @"C:\temp\destination"; Copy(sourceDirectory, targetDirectory); Console.WriteLine("\r\nEnd of program"); Console.ReadKey(); } public static void Copy(string sourceDirectory, string targetDirectory) { var diSource = new DirectoryInfo(sourceDirectory); var diTarget = new DirectoryInfo(targetDirectory); CopyAll(diSource, diTarget); } public static void CopyAll(DirectoryInfo source, DirectoryInfo target) { Directory.CreateDirectory(target.FullName); // Copy each file into the new directory. foreach (FileInfo fi in source.GetFiles()) { Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name); fi.CopyTo(Path.Combine(target.FullName, fi.Name), true); } // Copy each subdirectory using recursion. foreach (DirectoryInfo diSourceSubDir in source.GetDirectories()) { DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name); CopyAll(diSourceSubDir, nextTargetSubDir); } } }
Happy coding! 🙂