14 Oct 2009 @ 15:17 

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...
    }
}
Posted By: HoL1n
Last Edit: 01 Nov 2009 @ 18:59

EmailPermalinkComments (1)
Tags
Tags:
Categories: C#
Change Theme...
  • Users » 66
  • Posts/Pages » 14
  • Comments » 14
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight