Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exact file extension match with GetFiles()?

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!

like image 255
John Avatar asked Apr 06 '11 21:04

John


2 Answers

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.

like image 173
Fredrik Mörk Avatar answered Sep 21 '22 06:09

Fredrik Mörk


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();
like image 28
Chuck Savage Avatar answered Sep 22 '22 06:09

Chuck Savage