Copy Directory and Sub Directory
Today I will discuss this a method to copy the entire directory along with associated sub directories if required..
Here is the code snippet to achieve this:
/// <summary> /// Copys directory, including sub directories, if desired /// </summary> /// <param name="theSourcePath"></param> /// <param name="theDestPath"></param> /// <param name="copySubDirs"></param> private static void CopyDirectory(String theSourcePath, string theDestPath, bool copySubDirs) { var dir = new DirectoryInfo(theSourcePath); DirectoryInfo[] dirs = dir.GetDirectories(); // If the source directory does not exist, throw an exception. if (!dir.Exists) { throw new DirectoryNotFoundException( "Source directory does not exist or could not be found: " + theSourcePath); } // If the destination directory does not exist, create it. if (!Directory.Exists(theDestPath)) { Directory.CreateDirectory(theDestPath); } // Get the file contents of the directory to copy. FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) { // Create the path to the new copy of the file. string temppath = Path.Combine(theDestPath, file.Name); // Copy the file. file.CopyTo(temppath, false); } // If copySubDirs is true, copy the subdirectories. if (copySubDirs) { foreach (DirectoryInfo subdir in dirs) { // Create the subdirectory. string temppath = Path.Combine(theDestPath, subdir.Name); // Copy the subdirectories. CopyDirectory(subdir.FullName, temppath, true); } } }
No comments:
Post a Comment
Thank You for Your Comments. We will get back to you soon.