递归和非递归遍历文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了递归和非递归遍历文件相关的知识,希望对你有一定的参考价值。
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 遍历目录 { class Program { static void GetAllFiles(string dirPath) { List<string> list = new List<string>(); DirectoryInfo dir = new DirectoryInfo(dirPath); DirectoryInfo[] dirList = dir.GetDirectories(); for (int i = 0; i < dirList.Length; i++) { list.Add(dirList[i].FullName); GetAllFiles(dirList[i].FullName); } for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i]); } } static void GetAllFile2(string dirPath) { Stack<string> skDir = new Stack<string>(); skDir.Push(dirPath); while (skDir.Count > 0) { dirPath = skDir.Pop(); string[] subDirs = Directory.GetDirectories(dirPath); string[] subFiles = Directory.GetFiles(dirPath); if(subDirs != null) { for (int i = 0; i < subDirs.Length; i++) { //Path.GetFileName(subDirs[i]); skDir.Push(subDirs[i]); } } if (subFiles != null) { for (int i = 0; i < subFiles.Length; i++) { Console.WriteLine(subFiles[i]); } } } } static void Main(string[] args) { long startTime = DateTime.Now.Ticks; string dir = @"F:\开发资料"; GetAllFile2(dir); long endTime = DateTime.Now.Ticks; Console.WriteLine("耗时{0}", endTime - startTime); } } }
以上是关于递归和非递归遍历文件的主要内容,如果未能解决你的问题,请参考以下文章