Reputation: 47
I use this function to traverse all files in a directory and executing a code for each file only if it has a specific extension, like .txt in the example. I also exclude the ones ending with .png.
foreach (string file in Directory.EnumerateFiles(rootDir).Where(
f => (f.ToLower().EndsWith(".txt")) //Include
&& !(f.ToLower().EndsWith(".png")) //Exclude
).ToList())
{
//Do something
}
This code works fine, but what if I have to deal with several extensions?
I would whitelisting/blacklisting every extension writing the same line of code over and over again.
I'm sure a clever way exists. An idea is to store all the wanted and unwanted extension in an array.
How the code above could be improve in order to do this?
Upvotes: 0
Views: 339
Reputation: 17964
You can do something like this:
var whiteList = new List<string>{".txt"};
var blackList = new List<string>{".png"};
foreach (string file in
Directory
.EnumerateFiles(rootDir)
.Where(
f => whiteList.Any(ext => (f.ToLower().EndsWith(ext)) //Either use a white list
//f => !(blackList.Any(ext => (f.ToLower().EndsWith(ext))) //Or use a black list
).ToList())
Upvotes: 2