我想检索文件扩展名的精确匹配指定字符串列表。
DirectoryInfo的DI =新的DirectoryInfo (someValidPath); 名单,LT; FileInfo的> MYFILES =新的List<&的FileInfo GT;(); 的foreach(FileInfo的网络连接di.GetFiles(* TXT。)) { myFiles.Add(FI); }
我得到扩展文件*。txt的,但我也得到扩展名为 *。txtx ,所以我所编码达得到,其扩展名的文件的开始以的 TXT 。
这是不是我想要的。我需要抓住所有的文件名,做一个正则表达式匹配\\.txt $(我认为),或 .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()?
发布评论