简体   繁体   English

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

[英]Directory.GetFiles returns unexpected results with SearchPattern

I'm working on a batch program that process a big amount of files (more than 50 000 files) and I'm facing weird behavior with the Directory.GetFiles method.我正在处理一个处理大量文件(超过 50 000 个文件)的批处理程序,我正面临Directory.GetFiles方法的奇怪行为。

In the process I move files that matches the following search pattern "*.pdf", and get the files thanks to the Directory.GetFiles method : I was very surprised to see that sometimes I have .pdfa files moved.在此过程中,我移动与以下搜索模式“*.pdf”匹配的文件,并通过Directory.GetFiles方法获取文件:我很惊讶地看到有时我移动了 .pdfa 文件。

So I've checked the doc and it clearly states that if the search pattern contains an extension with 3 letters every files that have an extension that begins with the extension will be returned.所以我检查了文档,它清楚地指出,如果搜索模式包含一个带有 3 个字母的扩展名,每个扩展名以该扩展名开头的文件都将被返回。

I've tested with a simple program and It does not behave like stated in the doc, it only behaves like this in very rare occasion.我已经用一个简单的程序进行了测试,它的行为不像文档中所说的那样,它只在极少数情况下表现得像这样。

With this code :使用此代码:

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

I have this result :我有这个结果:

在此处输入图片说明

Do you have any explanation about this behavior ?你对这种行为有什么解释吗?

This is the expected behavior of the GetFiles method and it's same on Windows as well, if you search in directory with .pdf it will pick files with extensions这是 GetFiles 方法的预期行为,在 Windows 上也是如此,如果您使用.pdf在目录中搜索,它将选择带有扩展名的文件.pdfa or *.pdfaaa , you would need to put a Where() yourself like: .pdfa*.pdfaaa ,您需要自己放置一个Where()例如:

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

As you can see that when we search in windows It is giving the same result as your code was giving:正如您所看到的,当我们在 Windows 中搜索时,它给出的结果与您的代码给出的结果相同:

在此处输入图片说明

For the reason of why the GetFiles is behaving that way please have a look here and you might also want to look at this post as well出于GetFiles行为方式的原因, 请查看此处,您可能还想查看这篇文章

As explained by @luaan and by @hans-passant (thanks a lot !) I do not found the file with the .pdfa extension, because the 8.3 format is disabled on my hard drive.正如@luaan 和@hans-passant 所解释的(非常感谢!)我没有找到扩展名为 .pdfa 的文件,因为我的硬盘驱动器上禁用了 8.3 格式。

On a hard drive with the 8.3 format enabled, the method behaves like stated in the doc.在启用了 8.3 格式的硬盘驱动器上,该方法的行为与文档中所述相同。

The GetFiles has a different behavior with the setting enabled or not. GetFiles 具有不同的行为,无论是否启用设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM