C# 使用通配符删除多个文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8807209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deleting multiple files with wildcard
提问by prongs
You know that in linux it's easy but I can't just understand how to do it in C# on Windows. I want to delete all files matching the wildcard f*.txt. How do I go about going that?
你知道在 linux 中这很容易,但我不能只理解如何在 Windows 上的 C# 中做到这一点。我想删除所有与通配符匹配的文件f*.txt。我该怎么做呢?
采纳答案by Ry-
You can use the DirectoryInfo.EnumerateFilesfunction:
您可以使用该DirectoryInfo.EnumerateFiles功能:
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.)
(当然,您可能想要添加错误处理。)
回答by keyboardP
You can use the Directory.GetFilesmethod with the wildcard overload. This will return all the filenames that match your pattern. You can then delete these files.
您可以将Directory.GetFiles方法与通配符重载一起使用。这将返回与您的模式匹配的所有文件名。然后您可以删除这些文件。
回答by Brian Cryer
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:
我知道这已经得到了回答并且有一个很好的答案,但是在 .NET 4.0 和更高版本中有一个替代方案。使用Directory.EnumerateFiles(),因此:
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.
缺点DirectoryInfo.GetFiles()是它返回一个文件列表——99.9% 的时间都很好。缺点是如果文件夹包含数万个文件(这种情况很少见),那么它会变得非常慢,并且枚举匹配的文件要快得多。
回答by s1cart3r
I appreciate this thread is a little old now, but if you want to use linq then
我很欣赏这个线程现在有点旧,但是如果你想使用 linq 那么
Directory.GetFiles("f:\TestData", "*.zip", SearchOption.TopDirectoryOnly).ToList().ForEach(f => File.Delete(f));

