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!
If you are using C# 2.0 Isn't easier ?
Couldn't you just add an if and check the last four characters of the filename?
Try this:
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).
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.
Somewhat of a workaround, but you can filter out exact matches with the
Where
extesion method:Note that this will make a case insensitive matching of the extension.
I had a user-supplied pattern so many of the other answers didn't suit me. I ended up with this more general purpose solution: