Skip to content

Instantly share code, notes, and snippets.

@StickNitro
Created March 14, 2017 11:22
Show Gist options
  • Save StickNitro/63cd45cdcc96321564101d45a8518b75 to your computer and use it in GitHub Desktop.
Save StickNitro/63cd45cdcc96321564101d45a8518b75 to your computer and use it in GitHub Desktop.
Extended CopyDirectory to allow providing an array of sub-directories to ignore when copying
public void CopyDirectory(string source, string destination, string[] subdirsToIgnore)
{
// Get the subdirectories for the specified directory.
var dir = new DirectoryInfo(source);
var dirs = dir.GetDirectories();
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ source);
}
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destination))
{
Directory.CreateDirectory(destination);
}
// Get the files in the directory and copy them to the new location.
var files = dir.GetFiles();
foreach (var file in files)
{
var temppath = System.IO.Path.Combine(destination, file.Name);
file.CopyTo(temppath, false);
}
// Copy all of the subdirectories
foreach (var subdir in dirs)
{
if (Array.IndexOf(subdirsToIgnore, subdir.Name) >= 0)
{
continue;
}
var temppath = System.IO.Path.Combine(destination, subdir.Name);
CopyDirectory(subdir.FullName, temppath);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment