Saturday, 26 January 2013

Copy a Directory in C#

Copy a Directory in C#


Copies all folders and files to destination volume/network drive with the same name as the source directory.
    

Sometimes, directory structure is  so nested, at that time u may get following error message.

 Message    "The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters."  

Here is the example for copying Inetpub folder to D volume with the same name.

CopyDirectory(@"c:\inetpub", @"d:\")

static void CopyDirectory(String src, String dest)
{
try
{

    String srcpathroot = Path.GetPathRoot(src);
    String destpathroot = Path.GetPathRoot(dest);

   //First Create all Directories/Sub directories.

    String[] dirs = Directory.GetDirectories(src, "*", SearchOption.AllDirectories);
    foreach (String difVolume in dirs)
    {
                 
        String path = difVolume.Replace(srcpathroot, destpathroot);
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
    }

//Second Copy all files from Source to Destination with file overwrite.

    String[]szFiles = Directory.GetFiles(src,"*",SearchOption.AllDirectories);
    foreach (String srcFile in szFiles)
    {
        String destFile = srcFile.Replace(srcpathroot, destpathroot);
        File.Copy(srcFile, destFile, true);
    }

               

}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}
}


Tags:Copy Directory in C#,Folder Copy in C#,Copy a directory to different volume,Copy Folder to USB,Copy folder with same name,Copy Directory in .NET C#,Copy directory to network folder,Copy Directory to UNC folder,Copy Entire Folder,Copy Directory with contents