用递归及非递归方法返回文件夹下(包括子文件夹)文件个数
参考: http://www.cnblogs.com/hlxs/p/3760827.html
首先,为了获取文件夹下的子文件夹及文件及测试执行时间,我们引用 System.IO; System.Diagnostics;
1 using System.IO; 2 using System.Diagnostics;
C#使用递归获取文件数量
1 static long CountFilesByRecursion (string path) 2 { 3 long count= Directory.GetFiles (path).LongLength; //获取文件夹下的文件个数 4 5 string [] folders=Directory.GetDirectories (path); //获取子文件夹个数 6 7 if ( folders.Length == 0 ) //子文件夹个数为0时返回 8 { 9 return count; 10 } 11 else 12 { 13 foreach ( string s in folders ) //子文件夹不为0时,获取这些子文件夹的文件个数 14 { 15 count += CountFilesByRecursion (s); 16 } 17 return count; //返回结果 18 } 19 20 }
C#非递归方法
1 static long CountFiles (string path) 2 { 3 long count = 0; 4 Queue<string> folders = new Queue<string> (); //使用一个先进先出的集合 5 folders.Enqueue (path); //将根文件夹加入集合 6 7 do 8 { 9 string folder = folders.Dequeue (); //取出集合开始处的元素,并移除 10 11 count += Directory.GetFiles (folder).Length; //获取这个文件夹下的文件数量 12 13 foreach ( string f in Directory.GetDirectories (folder) ) //获取文件夹下的子文件夹 14 { 15 folders.Enqueue (f); //把子文件夹加入集合结尾处 16 } 17 } while ( folders.Count > 0 ); //当集合内无元素(即无子文件夹) 退出循环 18 19 return count; //返回结果 20 }
Ok,最后我们测试一下效率
1 static void Main (string[] args) 2 { 3 string path = @"E:\User"; //设置文件夹 4 5 Console.WriteLine ("By Recursion"); //递归获取 6 Stopwatch watch = Stopwatch.StartNew (); 7 long i = CountFilesByRecursion (path); 8 watch.Stop (); 9 Console.WriteLine ("Files Count :{0},Use Time: {1}\n", i.ToString (), watch.ElapsedMilliseconds.ToString ()); 10 11 12 Console.WriteLine ("Not Recuresion"); //非递归获取 13 Stopwatch watch2 = Stopwatch.StartNew (); 14 long x = CountFiles (path); 15 watch2.Stop (); 16 Console.WriteLine ("Files Count :{0},Use Time: {1}\n", x.ToString (), watch2.ElapsedMilliseconds.ToString ()); 17 18 19 Console.ReadKey (); 20 }
结果: <测试一个两G左右的文件夹大小>

有一个奇怪的问题,当第一次运行的时候,递归所需要的时间比第二次运行要多很多~
浙公网安备 33010602011771号