Skip to content

Instantly share code, notes, and snippets.

@mattjcowan
Created April 25, 2016 02:44
Show Gist options
  • Save mattjcowan/3f5215531b27b78484a71946dad18733 to your computer and use it in GitHub Desktop.
Save mattjcowan/3f5215531b27b78484a71946dad18733 to your computer and use it in GitHub Desktop.
// From: http://stackoverflow.com/questions/627504/what-is-the-best-way-to-recursively-copy-contents-in-c
public static void CopyDirectory(DirectoryInfo source, DirectoryInfo target, bool overwrite = true,
bool recurse = false, bool throwOnError = true)
{
try
{
//check if the target directory exists
if (Directory.Exists(target.FullName) == false)
{
Directory.CreateDirectory(target.FullName);
}
//copy all the files into the new directory
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), overwrite);
}
//copy all the sub directories using recursion
if (!recurse)
return;
foreach (var diSourceDir in source.GetDirectories())
{
var nextTargetDir = target.CreateSubdirectory(diSourceDir.Name);
CopyDirectory(diSourceDir, nextTargetDir, overwrite, true);
}
}
catch (IOException ex)
{
if (throwOnError)
throw;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment