c# - EnumerateFiles 中的配置 SearchPattern

标签 c# .net c#-4.0 directoryinfo

我有一个包含 2 个文件的目录:

  • 文件1.xls
  • 文件2.xlsx

如果我这样做:

directoryInfo.EnumerateFiles("*.xls", SearchOption.TopDirectoryOnly)

它返回两个文件,我只想要第一个 (file1.xls)。我该怎么做?

谢谢!

最佳答案

看起来在幕后,DirectoryInfo 类使用 Win32 调用 FindFirstFile .

这只允许通配符:

* 匹配任意字符

? 匹配 0 个或多个字符 - 参见 comments .

因此您必须自己过滤结果,可能使用以下方法:

directoryInfo.EnumerateFiles("*.xls", SearchOption.TopDirectoryOnly)
             .Where(fi => fi.Extension == ".xls");

关于c# - EnumerateFiles 中的配置 SearchPattern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10812199/

相关文章:

c# - 在 LocalMachine 存储或 CurrentUser 存储中找不到证书

.net - 为什么 UWP 类库项目引用被复制到主项目?

asp.net - .NET 中的垃圾收集器

c# 索引超出了数组的范围

c# - Entity Framework 查询outofmemoryexception

c#-4.0 - 如何解决无法连接到 IPC 端口错误

c# - 使用 C# 为独立应用程序进行 Google 或 Bing map 编程

c# - .NET 4 任务并行库可以使用 COM 对象吗?

c# - 如何使用字符串中的 XML 标记?

.net - IIS 7.0 错误 HTTP 错误 500.19 - 内部服务器错误(错误代码 0x80070003)