c# Directory

2021-03-23 18:26

阅读:389

标签:ati   cto   catch   enumerate   rect   efi   sea   bsp   reac   

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:\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
-----------------------

 

c# Directory

标签:ati   cto   catch   enumerate   rect   efi   sea   bsp   reac   

原文地址:https://www.cnblogs.com/wyvern0618/p/9454924.html


评论


亲,登录后才可以留言!