Programming
C# – Copy Folder Recursively
by admin on Feb.28, 2012, under Programming
I recently faced the problem of being unable to copy a directory recursively in C-Sharp. I therefore searched around the internet and found a pretty neat solution on the web. In order to copy a directory recursively, all you have to do is write a recursive function copying all files inside the folder which calls itself whenever a sub-directory is about to be copied. The following example code demonstrates how to copy a directory recursively.
private void CopyFolderRecursively(string sourceFolder, string destFolder) { if (!System.IO.Directory.Exists(destFolder)) System.IO.Directory.CreateDirectory(destFolder); string[] files = System.IO.Directory.GetFiles(sourceFolder); foreach (string file in files) { string name = System.IO.Path.GetFileName(file); string dest = System.IO.Path.Combine(destFolder, name); System.IO.File.Copy(file, dest); } string[] folders = System.IO.Directory.GetDirectories(sourceFolder); foreach (string folder in folders) { string name = System.IO.Path.GetFileName(folder); string dest = System.IO.Path.Combine(destFolder, name); CopyFolderRecursively(folder, dest); } }