文件通过文件名模式存在


78

我在用:

File.Exists(filepath)

我想做的就是将其切换为一种模式,因为文件名的第一部分发生了变化。

例如:文件可能是

01_peach.xml
02_peach.xml
03_peach.xml

如何根据某种搜索模式检查文件是否存在?

Answers:


120

您可以使用模式检查目录列表以检查文件

string[] files = System.IO.Directory.GetFiles(path, "*_peach.xml", System.IO.SearchOption.TopDirectoryOnly);
if (files.Length > 0)
{
    //file exist
}

68

如果您使用的是.net Framework 4或更高版本,则可以使用 Directory.EnumerateFiles

bool exist = Directory.EnumerateFiles(path, "*_peach.xml").Any();

Directory.GetFiles由于可以避免遍历整个文件列表,因此这可能比使用效率更高。


您的代码版本具有相同的功能,但是是隐藏的。无法一无所有地获得所有与模式匹配的文件。
Kostadin

4
@Kostadin:错过了回答这个问题……他不想让所有文件都匹配某个模式,他想知道是否有任何文件
Claudio Redi

如果卡在3.5中,则可以使用bool存在= Directory.GetFiles(path,“ * _peach.xml”)。Any();
乔·约翰斯顿

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.