使用通配符删除多个文件

你知道在 linux 中这很容易,但是我不能理解如何在 Windows 中用 C # 做到这一点。我想删除所有匹配通配符 f*.txt的文件。我该怎么做呢?

65333 次浏览

You can use the Directory.GetFiles method with the wildcard overload. This will return all the filenames that match your pattern. You can then delete these files.

You can use the DirectoryInfo.EnumerateFiles function:

var dir = new DirectoryInfo(directoryPath);


foreach (var file in dir.EnumerateFiles("f*.txt")) {
file.Delete();
}

(Of course, you'll probably want to add error handling.)

I know this has already been answered and with a good answer, but there is an alternative in .NET 4.0 and higher. Use Directory.EnumerateFiles(), thus:

foreach (string f in Directory.EnumerateFiles(myDirectory,"f*.txt"))
{
File.Delete(f);
}

The disadvantage of DirectoryInfo.GetFiles() is that it returns a list of files - which 99.9% of the time is great. The disadvantage is if the folder contains tens of thousands of files (which is rare) then it becomes very slow and enumerating through the matching files is much faster.

I appreciate this thread is a little old now, but if you want to use linq then

Directory.GetFiles("f:\\TestData", "*.zip", SearchOption.TopDirectoryOnly).ToList().ForEach(File.Delete);