c# - Directory.GetFiles 使用 SearchPattern 返回意外结果

标签 c# .net base-class-library system.io.directory

我正在开发一个处理大量文件(超过 50000 个文件)的批处理程序,并且我在使用 Directory.GetFiles 方法时遇到了奇怪的行为。

在此过程中,我移动与以下搜索模式“*.pdf”匹配的文件,并通过 Directory.GetFiles 方法获取文件: 有时我会移动 .pdfa 文件,这让我感到非常惊讶。

所以我检查了 doc并且它明确指出,如果搜索模式包含 3 个字母的扩展名,则将返回扩展名以该扩展名开头的每个文件。

我已经用一个简单的程序进行了测试,它的行为与文档中所述的不一样,它只在极少数情况下才会这样。

使用此代码:

static void Main(string[] args) {
    var directory = @"E:\Test\";
    var files = Directory.GetFiles(directory, "*.pdf");
    foreach(var file in files)
        Console.WriteLine(file);
}

我有这个结果:

enter image description here

你对这种行为有什么解释吗?

最佳答案

这是 GetFiles 方法的预期行为,在 Windows 上也是如此,如果您在目录中搜索 .pdf 它将选择文件扩展名 .pdfa*.pdfaaa,您需要自己放置一个 Where()喜欢:

Directory.GetFiles(directory, "*.pdf").Where(item => item.EndsWith(".pdf"));

如您所见,当我们在 Windows 中搜索时,它给出的结果与您的代码给出的结果相同:

enter image description here

为什么 GetFiles 会那样做 please have a look here你可能还想看看 this post as well

关于c# - Directory.GetFiles 使用 SearchPattern 返回意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42419525/

相关文章:

c# - 在 ListView 中对项目进行分组 - Windows 应用商店应用

c# - xaml d :DataContext giving "Access is denied" error

c# - 在 windows 窗体中实现加载器,如 web 应用程序

c# - async/await WhenAll 在两个具有相同返回类型的方法上

c# - 什么是 GetFullPath(String, String) 重载?

c# - System.Drawing.Color -state 有什么值(value)?

c# - WPF Datagrid-自动刷新

c# - .NET 内置 AVL 树?

c# - 从 XML 文件中删除所有艺术家节点

.net - 为什么.NET中没有SortedList <T>?