I found several examples how to copy a complete folder with c# and i want to share this script because for me it is the best and easiest solution. it is copy from the famous web-site csharp411
I’ve added some more functions to handle different scenarios, when the folder already exists or the files already exists.
In this example I’m setting ‘overwrite = true’ in the function File.Copy(file, dest, true);
public static void CopyFolder(string sourceFolder, string destFolder) { if (string.IsNullOrEmpty(sourceFolder)) { throw new ArgumentNullException("sourceFolder"); } if (string.IsNullOrEmpty(destFolder)) { throw new ArgumentNullException("destFolder"); } if (!Directory.Exists(sourceFolder)) { throw new ArgumentException("Source folder does not exist", "sourceFolder"); } try { 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, true); } string[] folders = Directory.GetDirectories(sourceFolder); foreach (string folder in folders) { string name = Path.GetFileName(folder); string dest = Path.Combine(destFolder, name); CopyFolder(folder, dest); } } catch (Exception er) { // Do something with this exception... } } |

Categories
Tag Cloud
Blog RSS
Comments RSS

Void « Default
Life
Earth
Wind
Water
Fire
Light 