59

我在运行时将文件保存在特定文件夹中。一段时间后,我想以编程方式删除它们。如何删除特定文件夹中的所有文件?

4

6 回答 6

138
string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
foreach (string filePath in filePaths)
File.Delete(filePath);

或者在一行中:

Array.ForEach(Directory.GetFiles(@"c:\MyDir\"), File.Delete);
于 2012-09-06T09:32:47.033 回答
15

您可以通过FileInfoDirectoryInfo做到这一点:

DirectoryInfo di = new DirectoryInfo("TempDir");
di.Delete(true);

然后重新创建目录

于 2012-09-06T09:33:53.697 回答
9
System.IO.DirectoryInfo myDirInfo = new DirectoryInfo(myDirPath);

foreach (FileInfo file in myDirInfo.GetFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in myDirInfo.GetDirectories())
{
    dir.Delete(true); 
}
于 2012-09-06T09:34:18.217 回答
5

添加以下命名空间,

using System.IO;

并使用Directory该类到达特定文件夹:

string[] fileNames = Directory.GetFiles(@"your directory path");
foreach (string fileName in fileNames)
    File.Delete(fileName);
于 2012-09-06T09:33:04.580 回答
3

尝试这个:

foreach (string file in Directory.GetFiles(@"c:\directory\"))
  File.Delete(file);
于 2012-09-06T09:33:40.853 回答
0

您可以执行以下操作:

Directory directory = new DirectoryInfo(path);
List<FileInfo> fileInfos = directory.EnumerateFiles("*.*", SearchOption.AllDirectories).ToList();
foreach (FileInfo f in fileInfos)
    File.Delete(f.FullName);
于 2012-09-06T09:34:03.017 回答