Reputation: 9080
I have 140 directories that I'm trying to process. According to my tests there are 139 directories that match my file pattern (*abc.txt).
I'm trying to find the 1 directory to verify that in fact it does not have a *abc.txt in it.
How can I do this?
The following code gives me the 140 directories number:
var directoryCount = from subdirectory in Directory.GetDirectories(paramStartFilePath, "*", SearchOption.AllDirectories)
where Directory.GetDirectories(subdirectory).Length == 0
select subdirectory;
I'm gathering the files based off the pattern like this:
dirInfoFiles= new DirectoryInfo(startFilePath);
IEnumerable<FileInfo> listFiles = dirInfoFiles.EnumerateFiles("*abc.txt, System.IO.SearchOption.AllDirectories);
How can I find the the one directory that doesn't contain my .txt file?
Upvotes: 1
Views: 3203
Reputation: 1074
Here is my take. It returns the first item (or null) that contains a file ending with the text you are looking for and is case insensitive. You could remove the lambdas to make it more readable.
var directory = Directory.GetDirectories((paramStartFilePath, "*", SearchOption.AllDirectories)
.FirstOrDefault(x => new DirectoryInfo(x).EnumerateFiles().Any(f => !f.Name.EndsWith("abc.txt",true,CultureInfo.CurrentCulture)));
Upvotes: 0
Reputation: 460028
If you want all directories that does not contain at least one txt-file which name ends with "abc":
IEnumerable<DirectoryInfo> matchingDirs = dirInfoFiles.EnumerateDirectories("*.*", System.IO.SearchOption.AllDirectories)
.Where(d => !d.EnumerateFiles().Any(f => f.Extension.ToUpper() == ".TXT"
&& f.Name.EndsWith("abc", StringComparison.OrdinalIgnoreCase)));
or the same in other words, possibly more readable:
IEnumerable<DirectoryInfo> matchingDirs = dirInfoFiles
.EnumerateDirectories("*.*", System.IO.SearchOption.AllDirectories)
.Where(d => !d.EnumerateFiles("*abc.txt").Any());
Upvotes: 1
Reputation: 61596
There is always the running the tank through the village approach: just enumerate *.*
and then exclude the patterns that don't match.
Upvotes: 2