Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 870
MadBoy Avatar asked Dec 12 '10 19:12

MadBoy


People also ask

Can you call directory GetFiles () with multiple filters?

If you have a list of X extensions, then it will be X times more slow. Because here you are calling the function Directory. GetFiles several times, whereas in the other solution it is called only once.

What is Directory GetFiles?

GetFiles(String, String, SearchOption) Returns the names of files (including their paths) that match the specified search pattern in the specified directory, using a value to determine whether to search subdirectories.


1 Answers

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));
like image 164
SLaks Avatar answered Sep 30 '22 17:09

SLaks