///Note that all files at the source folder have been copied to the destination folder. But folder and files within them have been copied using recursion - see the function of second foreach construct./// Copy folder to another folder recursively /// /// /// public static void CopyFolder(string sourceFolder, string destFolder) { if (!Directory.Exists(destFolder)) Directory.CreateDirectory(destFolder); string[] files = Directory.GetFiles(sourceFolder); foreach (string file in files) { string name = Path.GetFileName(file); string dest = Path.Combine(destFolder, name); File.Copy(file, dest); } string[] folders = Directory.GetDirectories(sourceFolder); foreach (string folder in folders) { string name = Path.GetFileName(folder); string dest = Path.Combine(destFolder, name); CopyFolder(folder, dest); } }
Shortcomings? Yes, no exception handling has been done in the snippet. However, the functionality is ok! Thanks to csharp411.com.
2 comments:
Thank you so much for the solution. helped me a lot.
Thanks for this perfect solution. I would only add the overwrite option in the file.copy parameters to avoid exceptions when the file already exists:
File.Copy(file, dest, true);
Post a Comment
Hope you liked this post. You can leave your message or you can put your valuable suggestions on this post here. Thanks for the sharing and cooperation!