I'd like to retrieve a list of files whose extensions match a specified string exactly.
DirectoryInfo di = new DirectoryInfo(someValidPath);
List<FileInfo> myFiles = new List<FileInfo>();
foreach (FileInfo fi in di.GetFiles("*.txt"))
{
myFiles.Add(fi);
}
I get the files with extension *.txt
but I also get files with the extension *.txtx
, so what I've coded amounts to getting the files whose extension starts with txt
.
This isn't what I want. Do I need to grab all of the filenames and do a regular expression match to "\\.txt$"
(I think), or test each filename string with .EndsWith(".txt")
, etc., to accomplish this?
Thanks!
Somewhat of a workaround, but you can filter out exact matches with the Where
extesion method:
foreach (FileInfo fi in di.GetFiles("*.txt")
.Where(fi => string.Compare(".txt", fi.Extension, StringComparison.OrdinalIgnoreCase) == 0))
{
myFiles.Add(fi);
}
Note that this will make a case insensitive matching of the extension.
Using the AddRange feature of lists instead of doing the foreach loop and calling Add for each item returned by the expression below (which I save into the variable list).
var list = di.GetFiles("*.txt").Where(f => f.Extension == ".txt");
myFiles.AddRange(list);
I'm presuming you were just showing us a snippet of your code and myFiles already had values in it, if not, you could do instead.
List<FileInfo> myFiles = di.GetFiles("*.txt").Where(f => f.Extension == ".txt").ToList();
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