Created
September 4, 2017 17:25
-
-
Save JekRock/d940724cb07f39b94a987d6ee8203cff to your computer and use it in GitHub Desktop.
Copy directory with directory structure
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
using System; | |
using System.IO; | |
class DirectoryCopyExample | |
{ | |
static void Main() | |
{ | |
// Copy from the current directory, include subdirectories. | |
DirectoryCopy(".", @".\temp", true); | |
} | |
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs) | |
{ | |
// Get the subdirectories for the specified directory. | |
DirectoryInfo dir = new DirectoryInfo(sourceDirName); | |
if (!dir.Exists) | |
{ | |
throw new DirectoryNotFoundException( | |
"Source directory does not exist or could not be found: " | |
+ sourceDirName); | |
} | |
DirectoryInfo[] dirs = dir.GetDirectories(); | |
// If the destination directory doesn't exist, create it. | |
if (!Directory.Exists(destDirName)) | |
{ | |
Directory.CreateDirectory(destDirName); | |
} | |
// Get the files in the directory and copy them to the new location. | |
FileInfo[] files = dir.GetFiles(); | |
foreach (FileInfo file in files) | |
{ | |
string temppath = Path.Combine(destDirName, file.Name); | |
file.CopyTo(temppath, false); | |
} | |
// If copying subdirectories, copy them and their contents to new location. | |
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