2016-02-26 27 views
1

我使用下面的代碼:Directory.GetFiles(...)帶模式*。返回有趣的結果

var di = new DirectoryInfo("path/to/dir"); 
var matchingFiles = di.GetFiles("*.???); 

正如預期的那樣,文件,如

  • file.bat
  • test.1.xml
  • a.txt.txt

被返回。但是,有一些有趣的結果。如the MS-documentation所述,短名也被搜索到。我還發現the information about the dot-selector working in .NET 4+。不過我看不出這也解釋了以下結果:

  • file1.xml.2
  • afilewithoutextension

Q1:這怎麼結果進行解釋。

Q2:如何實現模式匹配*。[3個任意字符]。

+0

嘗試添加'SearchOption.TopDirectoryOnly':'Directory.GetFiles(「path/to/dir」,「*。???」,SearchOption.TopDirectoryOnly)' –

回答

2

這怎麼結果進行解釋。

正如你注意到的,短名稱總是被搜索;並且它們總是具有三個字符的擴展名(即使這些字符是空格)。

如何實現模式*。[3個任意字符]的匹配。

檢查你的代碼(例如使用正則表達式)。 MS-DOS通配符非常有限,向後兼容性要求使它們更弱;它們實際上只對特定的匹配有用而不是通用的過濾。

+0

任何短名稱的來源始終具有'.3'部分? – ChriPf

+0

@ChriPf FAT目錄的底層數據結構。 – Richard

3

Q2),你可以使用LINQPath class代替:

var files = Directory.EnumerateFiles("path/to/dir", "*.*") 
    .Where(file => Path.GetExtension(file).TrimStart('.').Length == 3);