我正在使用:
File.Exists(filepath)
我想将其替换为模式,因为文件名的第一部分发生了变化。
例如:文件可能是
01_peach.xml
02_peach.xml
03_peach.xml
如何根据某种搜索模式检查文件是否存在?
您可以使用模式创建目录列表来检查文件
string[] files = System.IO.Directory.GetFiles(path, "*_peach.xml", System.IO.SearchOption.TopDirectoryOnly);
if (files.Length > 0)
{
//file exist
}
如果您使用 .net Framework 4 或更高版本,您可以使用
Directory.EnumerateFiles
bool exist = Directory.EnumerateFiles(path, "*_peach.xml").Any();
这可能比使用
Directory.GetFiles
更有效,因为您可以避免迭代整个文件列表。
要针对特定模式进行更高级的搜索,可能值得使用文件全局搜索,它允许您像在 .gitignore 文件中一样使用搜索模式。
请参阅此处:https://learn.microsoft.com/en-us/dotnet/core/extensions/file-globbing
这允许您将包含项和排除项添加到您的搜索中。
请参阅下面来自上述 Microsoft 源代码的示例代码片段:
Matcher matcher = new Matcher();
matcher.AddIncludePatterns(new[] { "*_peach.xml" });
IEnumerable<string> matchingFiles = matcher.GetResultsInFullPath(filepath);