C#遍历文件夹及其子目录的完整实现方法
程序员文章站
2022-05-18 14:24:02
本文实例讲述了c#遍历文件夹及其子目录的完整实现方法。分享给大家供大家参考,具体如下:
using system;
using system.collectio...
本文实例讲述了c#遍历文件夹及其子目录的完整实现方法。分享给大家供大家参考,具体如下:
using system; using system.collections; using system.collections.generic; using system.io; using system.security.accesscontrol; using system.text; namespace consoleapplication1 { class program { static void main(string[] args) { console.writeline("stt"); string str = @"e:\"; if (!str.endswith("\\")) { str += "\\"; } ilist<fileinfo> lst = getfiles(str); if (!directory.exists(str)) { try { directory.createdirectory(str); } catch(exception e) { console.writeline(e.message); console.readkey(); return; } } if (file.exists(str + "test.txt")) { file.delete(str + "test.txt"); } fileinfo file = new fileinfo(str + "test.txt"); if (!file.directory.exists) { directory.createdirectory(file.directoryname); } using (streamwriter outfilewriter = new streamwriter(str + "test.txt", false, encoding.utf8)) { stringbuilder sb = new stringbuilder(); foreach (fileinfo item in lst) { sb.append("\""); sb.append(item.fullname); sb.append("\""); sb.append(","); sb.append("\r\n"); } sb.remove(sb.length - 2, 2); outfilewriter.writeline(sb.tostring()); outfilewriter.flush(); outfilewriter.close(); } console.writeline("end"); console.readkey(); } private static void getdirectorys(string strpath, ref list<string> lstdirect) { directoryinfo difliles = new directoryinfo(strpath); directoryinfo[] diarr = difliles.getdirectories(); //directorysecurity directorysecurity = null; foreach (directoryinfo di in diarr) { try { //directorysecurity = new directorysecurity(di.fullname, accesscontrolsections.access); //if (!directorysecurity.areaccessrulesprotected) //{ lstdirect.add(di.fullname); getdirectorys(di.fullname, ref lstdirect); //} } catch { continue; } } } /// <summary> /// 遍历当前目录及子目录 /// </summary> /// <param name="strpath">文件路径</param> /// <returns>所有文件</returns> private static ilist<fileinfo> getfiles(string strpath) { list<fileinfo> lstfiles = new list<fileinfo>(); list<string> lstdirect = new list<string>(); lstdirect.add(strpath); directoryinfo difliles = null; getdirectorys(strpath, ref lstdirect); foreach (string str in lstdirect) { try { difliles = new directoryinfo(str); lstfiles.addrange(difliles.getfiles()); } catch { continue; } } return lstfiles; } } }
更多关于c#相关内容感兴趣的读者可查看本站专题:《c#遍历算法与技巧总结》、《c#程序设计之线程使用技巧总结》、《c#操作excel技巧总结》、《c#中xml文件操作技巧汇总》、《c#常见控件用法教程》、《winform控件用法总结》、《c#数据结构与算法教程》、《c#数组操作技巧总结》及《c#面向对象程序设计入门教程》
希望本文所述对大家c#程序设计有所帮助。