为什么带SearchPattern的getFiles()没有给出确切的结果?

时间:2016-08-26 01:14:49

标签: .net vb.net

我使用搜索模式GetFiles使用此代码:

Dim wordFiles As FileInfo()= New DirectoryInfo(source).GetFiles("*.doc")

source目录中的文件是:

  1. Test.doc的
  2. Test1.docx
  3. test3.docxxx
  4. test2.doc_xxx
  5. 为什么我收到的文件不具备确切的搜索模式?我明白了:

    1. Test.doc的
    2. Test1.docx&#39; <预期
    3. test2.doc_xxx&#39; <预期
    4. 我只期望&#39; Test.doc&#39;作为输出文件。

2 个答案:

答案 0 :(得分:2)

MSDN says这是预期的行为:

  

在searchPattern中使用星号通配符(例如“* .txt”)时,匹配行为会根据指定文件扩展名的长度而有所不同。具有正好三个字符的文件扩展名的searchPattern将返回扩展名为三个或更多字符的文件,其中前三个字符与searchPattern中指定的文件扩展名匹配。

     

文件扩展名为一,二或三个以上字符的searchPattern仅返回扩展名与searchPattern中指定的文件扩展名完全匹配的文件。使用问号通配符时,此方法仅返回与指定文件扩展名匹配的文件。

     

例如,给定目录中的两个文件“file1.txt”和“file1.txtother”,搜索模式“file?.txt”仅返回第一个文件,而搜索模式为“file *。 txt“返回两个文件。

您可以在获得文件后过滤这些文件:

New DirectoryInfo(source).
    GetFiles("*.doc").
    Where(Function (t) t.Extension.Equals(".doc", StringComparison.OrdinalIgnoreCase)).
    ToArray()

答案 1 :(得分:0)

正如MSDN根据此链接所述:DirectoryInfo.GetFiles Method (String, SearchOption)

  

在searchPattern中使用星号通配符时(for   例如,&#34; * .doc&#34;),匹配行为取决于   指定文件扩展名的长度。带有文件的searchPattern   正好三个字符的扩展名返回带扩展名的文件   三个或更多字符,前三个字符匹配   searchPattern中指定的文件扩展名。一个searchPattern   文件扩展名为一个,两个或三个以上的字符   仅返回扩展名完全匹配的文件   searchPattern中指定的文件扩展名。使用时   问号通配符,此方法仅返回文件   匹配指定的文件扩展名。例如,给出两个文件   目录,&#34; file1.txt&#34;和&#34; file1.txtother&#34;,搜索模式   &#34;文件的.txt&#34?;只返回第一个文件,而另一个搜索模式返回两个文件。

我冒昧地尝试为您找到解决方法,但似乎唯一可行的解​​决方案仅适用于.NET 4.0及更高版本:GetFiles with multiple and specific extentions c#

string[] patterns = new { ".xls", ".xlsx" };
return patterns.AsParallel().SelectMany(p => 
    Directory.EnumerateFiles(path, p, SearchOption.AllDirectories));
相关问题