确切的文件扩展名匹配的GetFiles()? [英] Exact file extension match with GetFiles()?
问题描述
我想检索文件扩展名的精确匹配指定字符串列表。
DirectoryInfo的DI =新的DirectoryInfo (someValidPath);
名单,LT; FileInfo的> MYFILES =新的List<&的FileInfo GT;();
的foreach(FileInfo的网络连接di.GetFiles(* TXT。))
{
myFiles.Add(FI);
}
我得到扩展文件*。txt的
,但我也得到扩展名为 *。txtx
,所以我所编码达得到,其扩展名的文件的开始以的 TXT
。
这是不是我想要的。我需要抓住所有的文件名,做一个正则表达式匹配\\.txt $
(我认为),或<测试每个文件名字符串code> .EndsWith(TXT)等,要做到这一点?
谢谢!
有点一种解决办法
,但是可以筛选出准确的其中,
extesion方法匹配
的foreach(FileInfo的网络连接di.GetFiles(* TXT)
。凡(FI = GT ;的String.Compare(,fi.Extension,StringComparison.OrdinalIgnoreCaseTXT)== 0))
{
myFiles.Add(FI);
}
请注意,这将使扩展的情况下不区分大小写的匹配。
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.
这篇关于确切的文件扩展名匹配的GetFiles()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!