如何删除所有文件但保持目录结构不变?

big*_*t42 -1 c#

我想删除文件夹中的所有文件,并删除其所有子文件夹和子子文件夹等中的所有文件,但我不想删除文件夹本身.

最简单的方法是什么?

Ser*_*rvy 7

foreach (var file in Directory.EnumerateFiles("path", "*", System.IO.SearchOption.AllDirectories))
{
    //TODO consider error handling
    File.Delete(file);
}
Run Code Online (Sandbox Code Playgroud)


eva*_*nal 5

  static void DirSearch(string sDir)
   {
       try
       {
           foreach (string d in Directory.GetDirectories(sDir))
           {
               foreach (string f in Directory.GetFiles(d))
               {
                   //Delete files, but not directories
                   File.Delete(f);
               }
               //Recursively call this method, so that each directory
               //in the structure is wiped
               DirSearch(d);
           }
       }
       catch (System.Exception excpt)
       {
           Console.WriteLine(excpt.Message);
       }
   }
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用库方法,而不是使用自己的递归函数手动遍历,这可以更有效地执行(并且不使用递归,因此消除了堆栈溢出异常的可能性). (2认同)