文件夹、文件操作
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++; } } } }