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 ?
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With