c# – 清空目录的最佳方法是什么?

前端之家收集整理的这篇文章主要介绍了c# – 清空目录的最佳方法是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法删除所有文件&指定目录的子目录而不迭代它们?

非优雅的解决方案:

  1. public static void EmptyDirectory(string path)
  2. {
  3. if (Directory.Exists(path))
  4. {
  5. // Delete all files
  6. foreach (var file in Directory.GetFiles(path))
  7. {
  8. File.Delete(file);
  9. }
  10.  
  11. // Delete all folders
  12. foreach (var directory in Directory.GetDirectories(path))
  13. {
  14. Directory.Delete(directory,true);
  15. }
  16. }
  17. }

解决方法

System.IO.Directory.Delete怎么样?它有一个递归选项,你甚至使用它.检查你的代码看起来你正试图做一些稍微不同的事情 – 清空目录而不删除它,对吧?好吧,你可以删除它并重新创建它:)

在任何情况下,您(或您使用的某些方法)必须遍历所有文件和子目录.但是,您可以使用GetFileSystemInfos同时迭代文件和目录:

  1. foreach(System.IO.FileSystemInfo fsi in
  2. new System.IO.DirectoryInfo(path).GetFileSystemInfos())
  3. {
  4. if (fsi is System.IO.DirectoryInfo)
  5. ((System.IO.DirectoryInfo)fsi).Delete(true);
  6. else
  7. fsi.Delete();
  8. }

猜你在找的C#相关文章