目前试了三种方法
1.递归
2.广度优先
3.Directory.GetFiles(path, "*", SearchOption.AllDirectories) 方法
但是试起来貌似最快的仍然是递归,有什么更好的方法么?
代码如下:
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; namespace ConsoleApp4 { class Program { static void Main(string[] args) { var path = @"E:\GIT"; //递归遍历文件夹 Stopwatch sw = new Stopwatch(); //遍历所有文件夹和文件 sw.Reset(); sw.Start(); all(path); sw.Stop(); Console.WriteLine("耗时:{0}", sw.ElapsedMilliseconds); sw.Start(); ListFiles(new DirectoryInfo(path), "-"); sw.Stop(); Console.WriteLine("耗时:{0}", sw.ElapsedMilliseconds); //广度优先遍历文件夹 sw.Reset(); sw.Start(); Traversing(path); sw.Stop(); Console.WriteLine("耗时:{0}", sw.ElapsedMilliseconds); Console.ReadKey(); } /// <summary> /// 递归遍历文件夹 /// </summary> /// <param name="info"></param> /// <param name="dep"></param> public static void ListFiles(FileSystemInfo info,string dep) { if (!info.Exists) return; DirectoryInfo dir = info as DirectoryInfo; if (dir == null) return; FileSystemInfo[] files = dir.GetDirectories(); foreach (var file in files) { if (file != null) { //Console.WriteLine("{0}{1}", dep, file.Name); //dep = dep + "-"; ListFiles(file, dep); } } } /// <summary> /// 广度优先算法遍历文件夹 /// </summary> /// <param name="sPathName"></param> public static void Traversing(string sPathName) { //创建一个队列保存子目录 Queue<string> pathQueue = new Queue<string>(); //首先将根目录排入队列中 pathQueue.Enqueue(sPathName); //开始循环查找文件,知道队列中无任何子目录 while (pathQueue.Count > 0) { //从队列中取出一个目录,把该目录下的所有目录排入队列中 DirectoryInfo dirParent = new DirectoryInfo(pathQueue.Dequeue()); foreach (var diChild in dirParent.GetDirectories()) { pathQueue.Enqueue(diChild.FullName); foreach (var fi in dirParent.GetFiles()) { // Console.WriteLine(fi.Name); } } } } public static void all(string path) { var x = 0; //获取所有文件 foreach (string f in Directory.GetFiles(path, "*", SearchOption.AllDirectories)) { //Console.WriteLine(f); x++; } //获取所有文件夹,只遍历文件的话似乎跟上面两个算法少了一步,所以又遍历了所有文件夹 foreach (string f in Directory.GetDirectories(path, "*", SearchOption.AllDirectories)) { //Console.WriteLine(f); x++; } } } }
我是来收藏代码的MAKE
0.0
我觉得,你这里的广度优先和递归没啥区别。你试出来的快慢的区别主要在于你创建对象的数量多少。。。。
+1,我是来收藏代码的MAKE