کلاس DirectoryInfo عملکرد پایهای برای دستیابی به یک دایرکتوری در فایل سیستم و دستکاری آن را فراهم میکند. برای جایجایی دایرکتوری متد MoveTo را دارد، اما برای کپی کردن آن خیر. کلاس Directory یک کلاس کمکی و یک واسط static را برای دستکاری و ایجاد دایرکتوریها در فایل سیستم است. برای جابجایی دایرکتوری متد Move را دارد، اما برای کپی کردن آن خیر. برای کپی کردن یک دایرکتوری به همراه فایلها و زیر دایرکتوریهای آن از متد زیر استفاده کنید.
1: private static void DirectoryCopy(
2: string sourceDirName, string destDirName, bool copySubDirs)
3: {4: DirectoryInfo dir = new DirectoryInfo(sourceDirName);
5: DirectoryInfo[] dirs = dir.GetDirectories(); 6: 7: // If the source directory does not exist, throw an exception.
8: if (!dir.Exists)
9: {10: throw new DirectoryNotFoundException(
11: "Source directory does not exist or could not be found: "
12: + sourceDirName); 13: } 14: 15: // If the destination directory does not exist, create it.
16: if (!Directory.Exists(destDirName))
17: { 18: Directory.CreateDirectory(destDirName); 19: } 20: 21: 22: // Get the file contents of the directory to copy.
23: FileInfo[] files = dir.GetFiles(); 24: 25: foreach (FileInfo file in files)
26: {27: // Create the path to the new copy of the file.
28: string temppath = Path.Combine(destDirName, file.Name);
29: 30: // Copy the file.
31: file.CopyTo(temppath, false);
32: } 33: 34: // If copySubDirs is true, copy the subdirectories.
35: if (copySubDirs)
36: { 37: 38: foreach (DirectoryInfo subdir in dirs)
39: {40: // Create the subdirectory.
41: string temppath = Path.Combine(destDirName, subdir.Name);
42: 43: // Copy the subdirectories.
44: DirectoryCopy(subdir.FullName, temppath, copySubDirs); 45: } 46: } 47: }