使用递归算法,实现删除,清空,拷贝一个文件夹。
using System.IO; namespace FileManagement { public class MyFileManager { /// <summary> /// 删除一个目录(空或非空) /// 1.先删除该目录下的所有文件 /// 2.再删除该目录下的所有子孙目录 /// 3.最后删除该目录(已成为空目录) /// </summary> /// <param name="dirName">目录名</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.删除所有的文件 /// 2.清空所有的子孙目录 /// 3.删除所有的子孙目录(已经成为空目录) /// </summary> /// <param name="DirName">目录名</param> public static void ClearDir(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) { ClearDir(dirName_); Directory.Delete(dirName_); } } /// <summary> /// 将一个目录下的内容拷贝到另一个目录下 /// </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]); } } } }