Exact file extension match with GetFiles()?

2020-02-06 07:20发布

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!

8条回答
看我几分像从前
2楼-- · 2020-02-06 07:49
DirectoryInfo di = new DirectoryInfo(someValidPath);
List<FileInfo> myFiles = new List<FileInfo>();
foreach (FileInfo fi in di.GetFiles("*.txt"))
{
   if (fi.Extension == ".txt")
      myFiles.Add(fi);
}
查看更多
霸刀☆藐视天下
3楼-- · 2020-02-06 07:52

Regex might be overkill. Use the extension on FileInfo.

foreach (FileInfo fi in di.GetFiles("*.txt").Where(f => f.Extension == ".txt"))
{
     myFiles.Add(fi);
} 
查看更多
登录 后发表回答