C#遍历目录下的所有文件夹

    技术2022-05-18  10

    using System; using System.Collections.Generic; using System.Text; using System.IO; namespace TestFileInfo { class Program { static void Main(string[] args) { string pathNames=null; do { Console.Write("请输入目录路径名(输入x退出程序):"); pathNames = Console.ReadLine(); if ((pathNames == "X") || (pathNames == "x")) break; DirectoryInfo dirPath = new DirectoryInfo(pathNames); CDirectoryInfo dirObject = new CDirectoryInfo(); Console.Write(dirObject.GetDirectoryInfos(dirPath)); Console.WriteLine("______________________________________________________/n"); dirObject.pathNameProp = null; Console.Write(dirObject.GetDirectoryInfos(pathNames)); Console.WriteLine("_____________________________________________________"); } while (true);//((pathName == "X") || (pathName == "x")); Console.Write("/n程序已终止,按任意键退出程序!"); Console.ReadKey(); } } class CDirectoryInfo { string pathName=null; public string pathNameProp { set { pathName = value; } get { return pathName; } } /// <summary> /// 遍历核心代码 /// </summary> /// <param name="fatherDir"></param> /// <returns></returns> public string GetDirectoryInfos(DirectoryInfo fatherDir) { try { DirectoryInfo[] childDir = fatherDir.GetDirectories(); if (childDir.Length == 0) //如果已无下层目录,则将当前目录的完整路径加入到pathName变量中 return pathName += fatherDir.FullName + "/n"; else { for (int i = 0; i < childDir.Length; i++) //如果有下层目录,则递归每一个下层目录,且在第一次循环时 { //将当前目录的完整路径加入到pathName变量中加入 if (i == 0) pathName += fatherDir.FullName + "/n"; GetDirectoryInfos(childDir[i]); } return pathName; } } catch (DirectoryNotFoundException ex) { return "你输入的路径无效,它可能不存在或者该路径拒绝访问。/n相关提示:/n" + ex.Message + "/n"; } catch (UnauthorizedAccessException ex) { return "你输入的路径无效,该路径可能拒绝访问。/n相关提示:/n" + ex.Message + "/n"; } } /// <summary> /// 遍历文件夹的重载函数 /// </summary> /// <param name="pathName"></param> /// <returns></returns> public string GetDirectoryInfos(string pathName) { try { DirectoryInfo fatherDir = new DirectoryInfo(pathName); DirectoryInfo[] childDir = fatherDir.GetDirectories(); if (childDir.Length == 0) return this.pathName += fatherDir.FullName + "/n"; else { for (int i = 0; i < childDir.Length; i++) { if (i == 0) this.pathName += fatherDir.FullName + "/n"; GetDirectoryInfos(childDir[i].FullName); } return this.pathName; } } catch (DirectoryNotFoundException ex) { return "你输入的路径无效,它可能不存在或者该路径拒绝访问。/n相关提示:/n" + ex.Message + "/n"; } catch (UnauthorizedAccessException ex) { return "你输入的路径无效,该路径可能拒绝访问。/n相关提示:/n" + ex.Message + "/n"; } } } }

    最新回复(0)