Created
June 14, 2013 11:53
-
-
Save sphingu/5781257 to your computer and use it in GitHub Desktop.
Directory Copy in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Function to copy all files from one directory to another( if destination dir not exist then create it ) | |
/// </summary> | |
/// <param name="sourceDirName">path of source directory</param> | |
/// <param name="destDirName">path of destination directory</param> | |
/// <param name="copySubDirs">want to copy sub directories or not</param> | |
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs) | |
{ | |
DirectoryInfo dir = new DirectoryInfo(sourceDirName); | |
DirectoryInfo[] dirs = dir.GetDirectories(); | |
if (!dir.Exists) | |
{ | |
throw new DirectoryNotFoundException("Source directory does not exist or could not be found: " | |
+ sourceDirName); | |
} | |
if (!Directory.Exists(destDirName)) | |
{ | |
Directory.CreateDirectory(destDirName); | |
} | |
FileInfo[] files = dir.GetFiles(); | |
foreach (FileInfo file in files) | |
{ | |
string temppath = Path.Combine(destDirName, file.Name); | |
if (!File.Exists(temppath)) | |
{ | |
file.CopyTo(temppath, false); | |
} | |
} | |
if (copySubDirs) | |
{ | |
foreach (DirectoryInfo subdir in dirs) | |
{ | |
string temppath = Path.Combine(destDirName, subdir.Name); | |
DirectoryCopy(subdir.FullName, temppath, copySubDirs); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment