使用 Directory.GetFiles 和搜索模式的 C# 递归目录 [英] C# Recurse Directories using Directory.GetFiles and search pattern

查看:102
本文介绍了使用 Directory.GetFiles 和搜索模式的 C# 递归目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用递归查找目录结构中的所有 excel 文件.问题是,Directory.GetFiles 中使用的搜索模式一次只允许一个扩展名.

I want to find all excel files within a directory structure using recursion. The problem is, the search pattern used in Directory.GetFiles only allows a single extension at a time.

有没有人知道解决这个问题的方法,或者我是否必须多次遍历目录以寻找特定的扩展名?或者您可以只抓取每个文件,然后遍历该列表以查找特定的扩展名.无论哪种方式听起来都有些低效.

Does anybody know a way around this or do I have to recurse through the directories multiple times looking for specific extensions? Or can you just grab every single file, and then loop through that list looking for specific extensions. Either way sounds a little inefficient.

谢谢

推荐答案

在 .NET 每个版本中都有 SearchOption.TopDirectoryOnly 和 SearchOption.AllDirectories

In .NET every version there is SearchOption.TopDirectoryOnly and SearchOption.AllDirectories

在 .NET 4 中,您可以非常有效地做到例如:

In .NET 4 you could very efficiently do e.g.:

        var regex = new Regex(@"\d+", RegexOptions.Compiled);

        var files = new DirectoryInfo(topdir)

            .EnumerateFiles("*.*", SearchOption.AllDirectories)

            .Where(fi => regex.IsMatch(fi.Name));

(此示例过滤名称中包含两位数字的文件)

(This example filters for files having two digits in the name)

为了模拟这一点,编写一个递归枚举器方法(yield return)来返回所有文件,并像这样过滤结果:

To emulate this, write a recursive enumerator method (yield return) to return all files, and filter the result like so:

 IEnumerable<FileInfo> Recurse(string topdir)
 { 
      // for each GetFiles() array element
      //      if is_not_dir yield return
      //      else Recurse(subdir)          
 }

 var filtered = Recurse.Where(fi => regex.IsMatch(fi.Name));

HTH

这篇关于使用 Directory.GetFiles 和搜索模式的 C# 递归目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆