Last active
December 18, 2015 01:59
-
-
Save murillomarigo/5707925 to your computer and use it in GitHub Desktop.
C# DirectoryInfoExtensions
- Directory CopyTo method (found at http://channel9.msdn.com/forums/TechOff/257490-How-Copy-directories-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
public static class DirectoryInfoExtensions | |
{ | |
/* | |
Usage | |
var source = new DirectoryInfo(@"C:\users\chris\desktop"); | |
source.CopyTo(@"C:\users\chris\desktop_backup", true); | |
*/ | |
public static void CopyTo(this DirectoryInfo source,string destDirectory, bool recursive) | |
{ | |
if (source == null) | |
throw new ArgumentNullException("source"); | |
if (destDirectory == null) | |
throw new ArgumentNullException("destDirectory"); | |
// If the source doesn't exist, we have to throw an exception. | |
if (!source.Exists) | |
throw new DirectoryNotFoundException("Source directory not found: " + source.FullName); | |
// Compile the target. | |
DirectoryInfo target = new DirectoryInfo(destDirectory); | |
// If the target doesn't exist, we create it. | |
if (!target.Exists) | |
target.Create(); | |
// Get all files and copy them over. | |
foreach (FileInfo file in source.GetFiles()) | |
{ | |
file.CopyTo(Path.Combine(target.FullName, file.Name), true); | |
} | |
// Return if no recursive call is required. | |
if (!recursive) | |
return; | |
// Do the same for all sub directories. | |
foreach (DirectoryInfo directory in source.GetDirectories()) | |
{ | |
CopyTo(directory, Path.Combine(target.FullName, directory.Name), recursive); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment