C#递归搜索指定目录下的文件或目录
诚然可以使用现成的Directory类下的GetFiles、GetDirectories、GetFileSystemEntries这几个方法实现同样的功能,但请相信我不是蛋疼,原因是这几个方法在遇上【System Volume Information】这种目录时,极有可能会给你个拒绝访问的异常,想跳过都不行。所以没办法,重新实现了一下。
实现说明 - 仍然是基于对Directory类的几个方法的封装进行实现,只是没有使用它们的searchPattern和searchOption功能
- 将匹配模式由windows的通配符?、*改为正则匹配。一是让匹配更强大,二是要实现?*匹配还得做额外工作,没必要
匹配模式并没有默认添加首尾限定^$,即“abc"将会匹配所有包含该字串的项目,所以如果你要匹配首尾,请自行添加^$
忽略大小写匹配
如果不想搜索指定项目而是全部,请将regexPattern参数设为null,而不是.*,前者性能更好
- 可通过设置recurse和throwEx参数决定是否递归搜索,和是否抛异常。默认是不递归,不抛异常
- 遇到不可访问的目录会跳过。当然前提是throwEx=false
- 之所以在foreach外层再套一层try-catch,是因为如果指定的dir就是不可访问的目录,那也可以避免异常
- 之所以为获取项、获取文件、获取目录分别实现3个方法,而不是只实现一个获取项,另外两个重载,是因为只实现一个的话,foreach中要做的逻辑判断不少,考虑到方法是要递归的,所以循环中逻辑越少越好
- 之所以不做dir参数合法性检查,原因同上,判断越少越好。所以请用户调用前自行确保dir合法 不废话,上代码:
/// <summary>
/// 获取指定目录中的匹配项(文件或目录)
/// </summary>
/// <param name="dir">要搜索的目录</param>
/// <param name="regexPattern">项名模式(正则)。null表示忽略模式匹配,返回所有项</param>
/// <param name="recurse">是否搜索子目录</param>
/// <param name="throwEx">是否抛异常</param>
/// <returns></returns>
private static string[] GetFileSystemEntries(string dir, string regexPattern = null, bool recurse = false, bool throwEx = false)
{
List<string> lst = new List<string>(); try
{
foreach (string item in Directory.GetFileSystemEntries(dir))
{
try
{
if (regexPattern == null || Regex.IsMatch(Path.GetFileName(item), regexPattern, RegexOptions.IgnoreCase | RegexOptions.Multiline))
{ lst.Add(item); } //递归
if (recurse && (File.GetAttributes(item) & FileAttributes.Directory) == FileAttributes.Directory)
{ lst.AddRange(GetFileSystemEntries(item, regexPattern, true)); }
}
catch { if (throwEx) { throw; } }
}
}
catch { if (throwEx) { throw; } } return lst.ToArray();
} /// <summary>
/// 获取指定目录中的匹配文件
/// </summary>
/// <param name="dir">要搜索的目录</param>
/// <param name="regexPattern">文件名模式(正则)。null表示忽略模式匹配,返回所有文件</param>
/// <param name="recurse">是否搜索子目录</param>
/// <param name="throwEx">是否抛异常</param>
/// <returns></returns>
private static string[] GetFiles(string dir, string regexPattern = null, bool recurse = false, bool throwEx = false)
{
List<string> lst = new List<string>(); try
{
foreach (string item in Directory.GetFileSystemEntries(dir))
{
try
{
bool isFile = (File.GetAttributes(item) & FileAttributes.Directory) != FileAttributes.Directory; if (isFile && (regexPattern == null || Regex.IsMatch(Path.GetFileName(item), regexPattern, RegexOptions.IgnoreCase | RegexOptions.Multiline)))
{ lst.Add(item); } //递归
if (recurse && !isFile) { lst.AddRange(GetFiles(item, regexPattern, true)); }
}
catch { if (throwEx) { throw; } }
}
}
catch { if (throwEx) { throw; } } return lst.ToArray();
} /// <summary>
/// 获取指定目录中的匹配目录
/// </summary>
/// <param name="dir">要搜索的目录</param>
/// <param name="regexPattern">目录名模式(正则)。null表示忽略模式匹配,返回所有目录</param>
/// <param name="recurse">是否搜索子目录</param>
/// <param name="throwEx">是否抛异常</param>
/// <returns></returns>
private static string[] GetDirectories(string dir, string regexPattern = null, bool recurse = false, bool throwEx = false)
{
List<string> lst = new List<string>(); try
{
foreach (string item in Directory.GetDirectories(dir))
{
try
{
if (regexPattern == null || Regex.IsMatch(Path.GetFileName(item), regexPattern, RegexOptions.IgnoreCase | RegexOptions.Multiline))
{ lst.Add(item); } //递归
if (recurse) { lst.AddRange(GetDirectories(item, regexPattern, true)); }
}
catch { if (throwEx) { throw; } }
}
}
catch { if (throwEx) { throw; } } return lst.ToArray();
}
C#递归搜索指定目录下的文件或目录的更多相关文章
- 9.proc目录下的文件和目录详解
1./proc目录下的文件和目录详解 /proc:虚拟目录.是内存的映射,内核和进程的虚拟文件系统目录,每个进程会生成1个pid,而每个进程都有1个目录. /proc/Version:内核版本 /pr ...
- 8.var目录下的文件和目录详解
1./var目录下的文件和目录详解. /var (该目录存放的是不断扩充且经常修改的目录,包括各种日志文件或者pid文件,存放linux的启动日志和正在运行的程序目录(变化的目录:一般是日志文件,ca ...
- Java递归输出指定路径下所有文件及文件夹
package a.ab; import java.io.File; import java.io.IOException; public class AE { public static void ...
- python_自动查找指定目录下的文件或目录的方法
代码如下 import os def find_file(search_path, file_type="file", filename=None, file_startswith ...
- Golang获取目录下的文件及目录信息
一.获取当前目录下的文件或目录信息(不包含多级子目录) func main() { pwd,_ := os.Getwd() //获取当前目录 //获取文件或目录相关信息 fileInfoList ...
- python笔记之按文件名搜索指定路径下的文件
1.搜索文件名中以指定的字符串开头(如搜索dll,结果中含有dll a,dll abc等) 我的目录下有dll a.txt和dll.txt文件 其中a文件夹下还有这两个文件 我希望通过python选择 ...
- 6.etc目录下重要文件和目录详解
1./etc/下的重要的配置文件 /etc(二进制软件包的 yum /rpm 安装的软件和所有系统管理所需要的配置文件和子目录.还有安装的服务的启动命令也放置在此处) /etc/sysconfig/n ...
- .gitignore排除(不忽略)二级以上目录下的文件或目录
在.gitignore中,结合使用/*和!filename的语法,可以达到除特定文件或目录外全部忽略的目的.但当希望不忽略的文件或目录在二级或多级目录下时,如果这样写 /* !/sub/subsub/ ...
- Linux—find在指定路径下查找文件或目录
find /指定路径 -name "*filename*" find /指定路径 -name "*filename*" 2>/dev/null ...
随机推荐
- tableView创建方法调用的研究
当两个section的cell数量都为5的时候,方法的调用顺序: -[ViewController numberOfSectionsInTableView:] -[ViewController tab ...
- iOS程序崩溃*** Terminating app due to uncaught exception 'CALayerInvalidGeometry', reason: 'CALayer position contains NaN: [37.5 nan]'
今天上班打开昨天的程序运行,昨天跑的很溜的程序今天竟然crash了,好郁闷啊!下面附上crash的栈打印信息: 经过一番调试终于找到了原因,程序crash是因为CALayer的位置中含有不存在的数,就 ...
- 低字节序和高字节序相互转换(Little Endian/Big Endian)
这个例子展示了如何转换整形数字的字节顺序,该方法可以用来在little-endian和big-endian之间转换. 说明:Windos(x86,x64)和Linux(x86,x64)都是little ...
- PHP简单计算器
工作之余,写着玩的. <?php $num1 = $_POST['num1']; $num2 = $_POST['num2']; $yusuan = $_POST['yusuan']; $jie ...
- underscorejs-where学习
2.7 where 2.7.1 语法: _.where(list, predicate) 2.7.2 说明: 对list集合的每个对象依次与predicate对象进行匹配,返回一个数组(数组为匹配成功 ...
- c#中使用easyUI的DataGrid组件
前台页面 html <table id="dg"> </table> JavaScript $("#dg").datagrid({ wi ...
- 初学Javascript对象
<script> var p=new Object(); //属性 p.width=; p.height=; p.num=; p.autotime=; //方法 p.autoplay=fu ...
- js 刷新页面大全
一.先来看一个简单的例子: 下面以三个页面分别命名为frame.html.top.html.bottom.html为例来具体说明如何做. frame.html 由上(top.html)下(bottom ...
- Python新手学习基础之函数-可变参数**
可变参数( ** ) 讲好了一颗*,那如果函数的最后一个参数带有 ** 前缀: 所有正常参数之外的其他的关键字参数都将被放置在一个字典中传递给函数. 要好好理解* 和 ** 两种可变参数哦~ 看个** ...
- JDBC驱动汇总
Microsoft SQL Server (6.5, 7, 2000 and 2005) and Sybase (10, 11, 12). ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ...