Directory.GetFiles使用SearchPattern返回意外结果 [英] Directory.GetFiles returns unexpected results with SearchPattern

查看:66
本文介绍了Directory.GetFiles使用SearchPattern返回意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个批处理程序,该程序处理大量文件(超过5万个文件),并且我遇到了 Directory.GetFiles 方法的怪异行为.

在此过程中,我将移动与以下搜索模式"* .pdf"匹配的文件,并通过 Directory.GetFiles 方法获得文件:看到有时我移动了.pdfa文件,我感到非常惊讶.

所以我检查了

您对此行为有任何解释吗?

解决方案

这是GetFiles方法的预期行为,如果您使用 .pdf在目录中搜索,则在Windows上也是如此.strong>会选择扩展名为 .pdfa *.pdfaaa 的文件,您需要自己放置 Where()像:

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

您可以看到,当我们在Windows中搜索时,它得到的结果与您的代码给出的结果相同:

由于 GetFiles 的行为,请在此处查看,您可能还希望查看Directory.GetFiles method : I was very surprised to see that sometimes I have .pdfa files moved.

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.

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 .pdfa or *.pdfaaa, you would need to put a Where() yourself like:

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:

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

这篇关于Directory.GetFiles使用SearchPattern返回意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆