I\'d like to retrieve a list of files whose extensions match a specified string exactly.
DirectoryInfo di = new DirectoryInfo(someValidPath);
List
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.
Couldn't you just add an if and check the last four characters of the filename?
If you are using C# 2.0 Isn't easier ?
string fileExtensionFilter = "*.txt";
DirectoryInfo di = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
List<FileInfo> myFiles = new List<FileInfo>();
foreach (FileInfo fi in di.GetFiles(fileExtensionFilter))
{
if (fi.Extension == fileExtensionFilter.Substring(1)) myFiles.Add(fi);
}
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);
}
Regex might be overkill. Use the extension on FileInfo.
foreach (FileInfo fi in di.GetFiles("*.txt").Where(f => f.Extension == ".txt"))
{
myFiles.Add(fi);
}
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();