C# 文件按文件名模式存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1199260/
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
file exists by file name pattern
提问by JL.
I am using:
我在用:
File.Exists(filepath)
What I would like to do is swop this out for a pattern, because the first part of the filename changes.
我想做的是把它换成一个模式,因为文件名的第一部分发生了变化。
For example: the file could be
例如:文件可能是
01_peach.xml
02_peach.xml
03_peach.xml
How can I check if the file exists based on some kind of search pattern?
如何根据某种搜索模式检查文件是否存在?
采纳答案by monkey_p
You can do a directory list with a pattern to check for files
你可以做一个带有模式的目录列表来检查文件
string[] files = System.IO.Directory.GetFiles(path, "*_peach.xml", System.IO.SearchOption.TopDirectoryOnly);
if (files.Length > 0)
{
//file exist
}
回答by Mitch Wheat
Get a list of all matching files using System.IO.DirectoryInfo.GetFiles()
使用System.IO.DirectoryInfo.GetFiles()获取所有匹配文件的列表
Also see SO Questions:
另见SO问题:
Is there a wildcard expansion option for .net apps?
How do I check if a filename matches a wildcard pattern
and many others...
和许多其他人...
回答by Claudio Redi
If you're using .net framework 4 or above you could use Directory.EnumerateFiles
如果您使用的是 .net framework 4 或更高版本,则可以使用 Directory.EnumerateFiles
bool exist = Directory.EnumerateFiles(path, "*_peach.xml").Any();
This could be more efficient than using Directory.GetFiles
since you avoid iterating trough the entire file list.
这可能比使用更有效,Directory.GetFiles
因为您可以避免遍历整个文件列表。