Directory類主要用於遍歷文件夾和文件。spa
調用EnumerateDirectories()等以Enumerate開頭的方法,則直接返回,在使用的時候才枚舉,提升了效率。code
public static void TestDirectory() { string dir = @"D:\FileTest"; if (Directory.Exists(dir)) { try { Console.WriteLine("-----------EnumerateFileSystemEntries------------"); var entries = Directory.EnumerateFileSystemEntries(dir,"*.*",SearchOption.AllDirectories); foreach (var e in entries) //在此行加斷點能夠發現,儘管dir中有大量文件,EnumerateFileSystemEntries依然直接返回。 { Console.WriteLine(e.ToString());//直到真正使用entries時,才進行枚舉。 } Console.WriteLine("-----------------------"); Console.WriteLine("-----------EnumerateDirectories------------"); var dirs = Directory.EnumerateDirectories(dir, "*.*", SearchOption.AllDirectories); foreach (var d in dirs) { Console.WriteLine(d.ToString()); } Console.WriteLine("-----------------------"); Console.WriteLine("-----------EnumerateFiles------------"); var files = Directory.EnumerateFiles(dir,"*.txt",SearchOption.AllDirectories); foreach (var f in files) { Console.WriteLine(f.ToString()); } Console.WriteLine("-----------------------"); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } }
結果:blog
-----------EnumerateFileSystemEntries------------
D:\FileTest\dir1
D:\FileTest\File_1.txt
D:\FileTest\File_2.txt
D:\FileTest\File_3.txt
D:\FileTest\dir1\File_11.txt
D:\FileTest\dir1\File_12.txt
-----------------------
-----------EnumerateDirectories------------
D:\FileTest\dir1
-----------------------
-----------EnumerateFiles------------
D:\FileTest\File_1.txt
D:\FileTest\File_2.txt
D:\FileTest\File_3.txt
D:\FileTest\dir1\File_11.txt
D:\FileTest\dir1\File_12.txt
-----------------------string