Recursive algorithm, delete, empty, copy a folder.
the using the System.IO; namespace FileManagement { public class MyFileManager { /// <Summary> /// remove a directory (empty or not) /// 1. delete all the files in the directory /// 2. delete All descendants of the directory in the directory /// 3. Finally, delete the directory (has become an empty directory) /// </ the Summary> /// <param name = "dirName"> directory name </ param> public static void RemoveDir ( String dirName) { IF (! Directory.Exists (dirName)) { return ; } string[] fileNames = Directory.GetFiles(dirName); string[] dirNames = Directory.GetDirectories(dirName); foreach (string fileName in fileNames) { File.Delete(fileName); } foreach (string dirName_ in dirNames) { RemoveDir(dirName_); } Directory.Delete(dirName); } /// <summary> /// 清空一个目录 ///1. Delete all files /// 2. Empty all of the descendants of the directory /// 3. Delete all of the descendants of the directory (has become an empty directory) /// </ the Summary> /// <param name = "DirName"> directory name </ param> public static void ClearDir ( String dirName) { IF (! Directory.Exists (dirName)) { return ; } String [] = fileNames the Directory.GetFiles (dirName); String [] = dirnames Directory.GetDirectories (dirName); the foreach ( String fileName fileNames)in { File.Delete (fileName); } the foreach ( String dirName_ in dirnames) { ClearDir (dirName_); Directory.Delete (dirName_); } } /// <Summary> /// the contents of a directory are copied to the other a directory /// </ Summary> /// <param name = "sourceDir"> </ param> /// <param name = "targetDir"> </ param> public static void copydir ( String sourceDir, String targetDir ) { if (!Directory.Exists(targetDir)) { Directory.CreateDirectory(targetDir); } string[] fileNames = Directory.GetFiles(sourceDir); string[] dirNames = Directory.GetDirectories(sourceDir); foreach (string fileName in fileNames) { File.Copy(fileName,targetDir + Path.DirectorySeparatorChar + Path.GetFileName(fileName),true); } foreach (string dirName_ in dirNames) { string[] splitStr = dirName_.Split(Path.DirectorySeparatorChar); CopyDir(dirName_, targetDir + Path.DirectorySeparatorChar + splitStr[splitStr.Length - 1]); } } } }