Directory类主要用于遍历文件夹和文件。
调用EnumerateDirectories()等以Enumerate开头的方法,则直接返回,在使用的时候才枚举,提高了效率。
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()); } } }
结果:
-----------EnumerateFileSystemEntries------------
D:FileTestdir1
D:FileTestFile_1.txt
D:FileTestFile_2.txt
D:FileTestFile_3.txt
D:FileTestdir1File_11.txt
D:FileTestdir1File_12.txt
-----------------------
-----------EnumerateDirectories------------
D:FileTestdir1
-----------------------
-----------EnumerateFiles------------
D:FileTestFile_1.txt
D:FileTestFile_2.txt
D:FileTestFile_3.txt
D:FileTestdir1File_11.txt
D:FileTestdir1File_12.txt
-----------------------