排除来自Directory.GetFiles结果 [英] Exclude results from Directory.GetFiles
问题描述
如果我要打电话 Directory.GetFiles ,并使其返回匹配模式 *。斌
这一点,但所有的文件,我要排除的所有文件,将匹配的模式日志#的.bin
,其中#
是不确定长度的运行计数器。有没有一种方法来筛选出来的结果在传递一个搜索过滤器的GetFiles
或必须得到的结果阵列的步骤,然后删除,我要排除的项目?
If I want to call Directory.GetFiles and have it return all files that match the pattern *.bin
but I want to exclude all of the files that would match the pattern LOG#.bin
where #
is a running counter of indeterminate length. Is there a way to filter out the results at the step of passing in a search filter to GetFiles
or must I get the result array then remove the items that I want to exclude?
推荐答案
您可以使用LINQ,<一个href="http://msdn.microsoft.com/en-us/library/system.io.directory.enumeratefiles.aspx"><$c$c>Directory.EnumerateFiles()$c$c>和其中()
过滤器 - 这样,你只结了你想要的文件,剩下的就是过滤掉
You can use Linq, Directory.EnumerateFiles()
and a Where()
filter - that way you only end up with the files you want, the rest is filtered out.
这样的事情应该工作:
Regex re = new Regex(@"^LOG\d+.bin$");
var logFiles = Directory.EnumerateFiles(somePath, "*.bin")
.Where(f => !re.IsMatch(Path.GetFileName(f)))
.ToList();
正如 Directory.EnumerateFiles
需要.NET 4.0。另外一个有点清洁的解决方案(在多一点的开销成本)正在使用的DirectoryInfo
/ EnumerateFiles()
返回一个的IEnumerable&LT; FileInfo的&GT;
,所以你可以直接访问的文件名和没有进一步的解析扩展
As pointed out Directory.EnumerateFiles
requires .NET 4.0. Also a somewhat cleaner solution (at the cost of a little more overhead) is using DirectoryInfo
/ EnumerateFiles()
which returns an IEnumerable<FileInfo>
so you have direct access to the file name and the extension without further parsing.
这篇关于排除来自Directory.GetFiles结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!