Directory.GetFiles() pattern match in C#

拜拜、爱过 提交于 2019-12-22 06:48:28

问题


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).

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);
}

I then call

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

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.

Would there be a better way to do so ?


回答1:


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

For example:

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));



回答2:


My final method based on SLaks answer for anyone looking for similar solution

private static IEnumerable<string> DirectoryGetFiles(string strDirName, SearchOption varOption) {
var extensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".zip", ".sfv" };
     extensions.UnionWith(Enumerable.Range(1, 999).Select(i => String.Format(".{0:000}", i)));
     extensions.UnionWith(Enumerable.Range(1, 99).Select(i => String.Format(".r{0:00}", i)));
     extensions.UnionWith(Enumerable.Range(1, 99).Select(i => String.Format(".s{0:00}", i)));
     extensions.UnionWith(Enumerable.Range(1, 99).Select(i => String.Format(".t{0:00}", i)));
     return Directory.EnumerateFiles(strDirName, "*.*", varOption).Where(p => extensions.Contains(Path.GetExtension(p))).ToList();
}


来源:https://stackoverflow.com/questions/4423429/directory-getfiles-pattern-match-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!