MadBoy
MadBoy

Reputation: 11114

Directory.GetFiles() pattern match in C#

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 ?

Upvotes: 5

Views: 3430

Answers (2)

MadBoy
MadBoy

Reputation: 11114

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

Upvotes: 0

SLaks
SLaks

Reputation: 888203

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

Upvotes: 5

Related Questions