c#递归遍历文件夹示例
程序员文章站
2023-12-19 18:41:40
代码很简单,指定需要递归遍历的文件夹和遍历规则就要可以运行了复制代码 代码如下:/// /// 递归获取文件夹目录下文件///
/// <summary>
/// 递归获取文件夹目录下文件
/// </summary>
/// <param name="pathname">需要递归遍历的文件夹</param>
/// <param name="filerule">遍历规则『委托』</param>
public static void loopfolder(string pathname, action<fileinfo> filerule)
{
if (string.isnullorempty(pathname))
throw new argumentnullexception(pathname);
csharptoolv2.loopfolder(@"c:\users\administrator\downloads\", (fileinfo file) =>
{
if (file.extension.equals(".xls"))//获取excel类型文件
{
console.writeline(string.format("============{0}==============", file.fullname));
}
代码很简单,指定需要递归遍历的文件夹和遍历规则就要可以运行了
复制代码 代码如下:
/// <summary>
/// 递归获取文件夹目录下文件
/// </summary>
/// <param name="pathname">需要递归遍历的文件夹</param>
/// <param name="filerule">遍历规则『委托』</param>
public static void loopfolder(string pathname, action<fileinfo> filerule)
{
if (string.isnullorempty(pathname))
throw new argumentnullexception(pathname);
queue<string> _pathqueue = new queue<string>();
_pathqueue.enqueue(pathname);
while (_pathqueue.count > 0)
{
string _path = _pathqueue.dequeue();
directorysecurity _pathsecurity = new directorysecurity(_path, accesscontrolsections.access);
if (!_pathsecurity.areaccessrulesprotected)//文件夹权限是否可访问
{
directoryinfo _directoryinfo = new directoryinfo(_path);
foreach (directoryinfo dichild in _directoryinfo.getdirectories())
{
_pathqueue.enqueue(dichild.fullname);
}
foreach (fileinfo file in _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));
}