文件按文件名模式存在

问题描述 投票:0回答:4

我正在使用:

File.Exists(filepath)

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

例如:文件可能是

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

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

c# .net-2.0 .net
4个回答
132
投票

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

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

80
投票

如果您使用 .net Framework 4 或更高版本,您可以使用

Directory.EnumerateFiles

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

这可能比使用

Directory.GetFiles
更有效,因为您可以避免迭代整个文件列表。



0
投票

要针对特定模式进行更高级的搜索,可能值得使用文件全局搜索,它允许您像在 .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);
© www.soinside.com 2019 - 2024. All rights reserved.