[C#]获取指定路径下所有文件(含所有子目录)文件全路径并获取文件大小
using System; using System.Collections; using System.Collections.Generic; using System.IO; namespace 遍历文件夹和子文件夹 { class Program { static void Main(string[] args) { string strWriteLinePath; int intLv = 0; Console.WriteLine("请输入路径:"); strWriteLinePath = Console.ReadLine(); strWriteLinePath.Replace('\\', '/'); Console.WriteLine("遍历结果如下:"); listDirectory(strWriteLinePath, intLv); Console.WriteLine("请按任意键继续……"); Console.ReadKey(); } public static string CountSize(long Size) { string m_strSize = ""; long FactSize = 0; FactSize = Size; if (FactSize < 1024.00) m_strSize = FactSize.ToString("F2") + " Byte"; else if (FactSize >= 1024.00 && FactSize < 1048576) m_strSize = (FactSize / 1024.00).ToString("F2") + " KByte"; else if (FactSize >= 1048576 && FactSize < 1073741824) m_strSize = (FactSize / 1024.00 / 1024.00).ToString("F2") + " MByte"; else if (FactSize >= 1073741824) m_strSize = (FactSize / 1024.00 / 1024.00 / 1024.00).ToString("F2") + " GByte"; return m_strSize; } public static int GetFilesCount(DirectoryInfo dirInfo) { int intTotFile = 0; intTotFile += dirInfo.GetFiles().Length;//获取全部文件 //totalFile += dirInfo.GetFiles("*.*").Length;//获取某种格式 foreach (System.IO.DirectoryInfo subdir in dirInfo.GetDirectories()) { intTotFile += GetFilesCount(subdir); } return intTotFile; } private static void listDirectory(string strPATH, int intLV) { DirectoryInfo theFolder = new(@strPATH); intLV++; int intResult = GetFilesCount(theFolder); Console.WriteLine("[" + strPATH + "]共含有" + intResult + "个文件"); //遍历文件 foreach (FileInfo File in theFolder.GetFiles()) { for (int i = 0; i < intLV; i++) Console.Write(""); string strFullPath = strPATH + "\\" + File.Name; Console.Write(strFullPath); string strSize = "\t" + File.Length + "字节" + "=" + CountSize(File.Length); Console.WriteLine(strSize); } //遍历文件夹 foreach (DirectoryInfo NextFolder in theFolder.GetDirectories()) { for (int i = 0; i < intLV; i++) Console.Write("-"); Console.Write(">"); Console.WriteLine(NextFolder.Name); listDirectory(NextFolder.FullName, intLV); } } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!