-4

我想删除子文件夹中的所有内容。

C:\Folder --> 根目录

A,B,C,D,.... --> 子文件夹(信息:有 247 个子文件夹)

我不知道如何实现它,例如在 c# 或批处理文件中。

我很感激任何帮助。

4

5 回答 5

5

对于第二个参数(递归),所有子文件夹都被删除!

Directory.Delete("yourpath", true);

如果要删除目录的内容,可以执行以下操作:

Directory.EnumerateFiles("yourpath", "*", SearchOption.AllDirectories).ToList().ForEach(f => File.Delete(f));
于 2013-09-16T10:11:59.347 回答
4

在批处理中它(也)很容易:

rmdir /S "C:\Folder"
于 2013-09-16T10:12:43.993 回答
1

在c#中

foreach(var file in Directory.EnumerateFiles(sourceDirectory, 
                   "*", SearchOption.AllDirectories))
{
    File.Delete(file);
}

或者

try
{
Directory.GetFiles(sourceDirectory, "*", SearchOption.AllDirectories)
     .ToList().ForEach(File.Delete);
}
catch(UnauthorizedAccessException uae)
{
}

注意:如果您没有对 sourceDirectory 的权限,这将不起作用(try catch 将防止两种情况下的应用程序错误)

于 2013-09-16T10:15:36.383 回答
0

在 c# 中,您可以这样做:

foreach(string directory in Directory.GetDirectories(@"C:\Folder"))
   Directory.Delete(directory, true);

您还可以将搜索模式传递​​给Directory.GetDirectories(...)

于 2013-09-16T10:14:31.723 回答
0

If you need to delete everything inside your root folder (all the subfolders and all the files in them, also files in root folder itself), then Yes Direcotry.Delete('path', true) is what you need.

But if you need to retain the sub folders (A,B,C,D) while still deleting all the files in them, then there is no Direct/BuiltIn way to do that, for that in general, you need to first get all the folder inside your root folder, then loop through them, then delete all the files inside them, leaving the subfolder empty.

Something like this method (call the method passing root path):

private void DeleteJustFilesFromFolder(string roootPath)
{
   DirectoryInfo d = new DirectoryInfo(roootPath);

   //delete files from root
   foreach (FileInfo fi in d.GetFiles())
   {
     fi.Delete();
   }

   //get root subfolders
   foreach (DirectoryInfo di in d.GetDirectories())
   {
      DeleteJustFilesFromFolder(di.FullName);

    //kept commented, but if you prefer then can delete subfolder by this line
    //di.Delete(); 
   }
}
于 2013-09-16T10:27:42.703 回答