C#中的Directory.GetFiles()模式匹配 [英] Directory.GetFiles() pattern match in C#

查看:1533
本文介绍了C#中的Directory.GetFiles()模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Directory.GetFiles()根据给定的模式列出文件.这对于我正在寻找的大多数模式都适用(例如zip,rar,sfv).

I'm using Directory.GetFiles() to list files according to given pattern. This works fine for most of patterns I'm looking for (e.g. zip, rar, sfv).

这是我准备列表的方式(或多或少).问题出在我要列出的.001到.999的数字模式上.

This is how I prepare the list (more or less). The problem is with pattern of numbers .001 to .999 that I want to list.

alArrayPatternText.Add("*.zip");
alArrayPatternText.Add("*.sfv");
alArrayPatternText.Add("*.r??");
alArrayPatternText.Add("*.001");
for (int i = 2; i <= 999; i++)
{
    string findNumber = String.Format("{0:000}", i);
    alArrayPatternText.Add("*." + findNumber);
}

然后我打电话

string[] files = Directory.GetFiles(strDirName, varPattern);

对于数组中的每个模式,这样做似乎是一个坏主意,因为列表中有1002个条目,并且检查目录中是否每个条目都有些耗时.

for each pattern in the Array which seems like very bad idea to do so since the list has 1002 entries and checking if directory has each of them is just a bit too time consuming.

会有更好的方法吗?

推荐答案

您应该调用Directory.EnumerateFiles("path", "*"),然后使用LINQ通过调用Path.GetExtension来过滤路径.

You should call Directory.EnumerateFiles("path", "*") and then use LINQ to filter the paths by calling Path.GetExtension.

例如:

var extensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
    ".zip", ".sfv"
};
extensions.UnionWith(Enumerable.Range(1, 998).Select(i => i.ToString(".000")));
var files = Directory.EnumerateFiles("path", "*")
            .Where(p => extensions.Contains(Path.GetExtension(p))
                     || Path.GetExtension(p).StartsWith(".r", StringComparison.OrdinalIgnoreCase));

这篇关于C#中的Directory.GetFiles()模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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