[C#]递归遍历文件夹

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

/// <summary>/// 递归获取文件夹目录下文件/// </summary>/// <param name="pathName">需要递归遍历的文件夹</param>/// <param name="fileRule">遍历规则『委托』</param>publicstaticvoidLoopFolder(stringpathName, Action<FileInfo> fileRule)

{if(string.IsNullOrEmpty(pathName))thrownewArgumentNullException(pathName);

Queue<string> _pathQueue =newQueue<string>();

_pathQueue.Enqueue(pathName);while(_pathQueue.Count > 0)

{string_path = _pathQueue.Dequeue();

DirectorySecurity _pathSecurity =newDirectorySecurity(_path,accessControlSections.Access);if(!_pathSecurity.AreAccessRulesPRotected)//文件夹权限是否可访问{

DirectoryInfo _directoryInfo =newDirectoryInfo(_path);foreach(DirectoryInfo diChildin_directoryInfo.GetDirectories())

{

_pathQueue.Enqueue(diChild.FullName);

}foreach(FileInfo filein_directoryInfo.GetFiles())

{

fileRule(file);

}

}

}

}

举例使用

CSharpToolV2.LoopFolder(@"C:\Users\Administrator\Downloads\", (FileInfo file) =>

{

if (file.Extension.Equals(".xls"))//获取Excel类型文件

{

Console.WriteLine(string.Format("============{0}==============", file.FullName));

}

});

.csharpcode, .csharpcode pre

{

font-size: small;

color: black;

font-family: consolas, "Courier New", courier, monospace;

background-color: #ffffff;

/*white-space: pre;*/

}

.csharpcode pre { margin: 0em; }

.csharpcode .rem { color: #008000; }

.csharpcode .kwrd { color: #0000ff; }

.csharpcode .str { color: #006080; }

.csharpcode .op { color: #0000c0; }

.csharpcode .preproc { color: #cc6633; }

.csharpcode .asp{ background-color: #ffff00; }

.csharpcode .html { color: #800000; }

.csharpcode .attr { color: #ff0000; }

.csharpcode .alt

{

background-color: #f4f4f4;

width: 100%;

margin: 0em;

}

.csharpcode .lnum { color: #606060; }代码效果

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航