.NET Framework中的DirectoryInfo.GetFiles方法,可以在一個文件夾下通過通配符找出符合條件的文件。
我們首先在文件夾C:\DemoFolder下定義兩個文件:demo.xls和demo.xlsx
然后我們新建一個.NET Framework控制台項目,然后在其Program類的Main方法中敲入如下代碼:
class Program { static void Main(string[] args) { DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\DemoFolder");//尋找在C:\DemoFolder文件夾下的文件 var files = directoryInfo.GetFiles("*.xls");//尋找文件夾下的所有.xls文件 foreach (var file in files) { Console.WriteLine(file.Name);//輸出找到的每個文件名 } Console.WriteLine("Press key to end..."); Console.ReadKey(); } }
這段代碼的本意是找出文件夾C:\DemoFolder下的所有.xls文件,但是我們看看輸出結果如下:
我們驚訝地發現,明明我們輸入DirectoryInfo.GetFiles方法的參數是*.xls,但是現在.xlsx后綴的文件也被找出來了。這個問題的根本原因是.NET Framework中,DirectoryInfo.GetFiles方法的通配符遵循了一套特殊的匹配規則,導致了*.xls匹配.xlsx后綴也是成功的。
微軟MSDN上對此的解釋如下:
The following list shows the behavior of different lengths for the searchPattern parameter: "*.abc" returns files having an extension of.abc,.abcd,.abcde,.abcdef, and so on. "*.abcd" returns only files having an extension of.abcd. "*.abcde" returns only files having an extension of.abcde. "*.abcdef" returns only files having an extension of.abcdef.
詳情請見下面MSDN鏈接的文章:
此外上面MSDN中也提到如果文件夾中的文件較多,推薦使用DirectoryInfo.EnumerateFiles方法效率更高,原因如下:
The EnumerateFiles and GetFiles methods differ as follows:
EnumerateFiles
When you use EnumerateFiles, you can start enumerating the collection of FileInfo objects before the whole collection is returned.
GetFiles
When you use GetFiles, you must wait for the whole array of FileInfo objects to be returned before you can access the array.
Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.
If there are no files in the DirectoryInfo, this method returns an empty array.
但是我測試了下本文所述問題在.NET Core中是不存在的,我們新建一個.NET Core控制台項目,然后復制粘貼上面Program類Main方法中的代碼到.NET Core控制台項目,執行結果如下:
可以看到.NET Core正確地找出了.xls后綴的文件,沒有找出.xlsx后綴的文件,所以目前來看本文所述問題只存在於.NET Framework中的DirectoryInfo.GetFiles和DirectoryInfo.EnumerateFiles方法上。
所以在.NET Framework中如果我們要用DirectoryInfo.GetFiles方法找出.xls后綴的文件,最保險的方法應該是下面這樣:
class Program { static void Main(string[] args) { DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\DemoFolder");//尋找在C:\DemoFolder文件夾下的文件 var files = directoryInfo.GetFiles().Where(f => f.Name.EndsWith(".xls")).ToArray();//尋找文件夾下的所有.xls文件 foreach (var file in files) { Console.WriteLine(file.Name);//輸出找到的每個文件名 } Console.WriteLine("Press key to end..."); Console.ReadKey(); } }
通過EndsWith方法可以准確找出以.xls后綴結尾的所有文件。