简体   繁体   中英

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!

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.

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();

Regex might be overkill. Use the extension on FileInfo.

foreach (FileInfo fi in di.GetFiles("*.txt").Where(f => f.Extension == ".txt"))
{
     myFiles.Add(fi);
} 

Try this:

DirectoryInfo di = new DirectoryInfo(someValidPath); 
List<FileInfo> myFiles =  
    (
        from file in di.GetFiles("*.txt")
        where file.Extension == ".txt"
        select file
    ).ToList();
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);
}

I had a user-supplied pattern so many of the other answers didn't suit me. I ended up with this more general purpose solution:

public string[] GetFiles(string path, string pattern)
{
    bool lastWildIsHook = false;
    if(pattern.EndsWith("?"))
    {
        pattern = pattern.Substring(0, pattern.Length - 1);
        lastWildIsHook = true;
    }
    var lastWildIndex = Math.Max(pattern.LastIndexOf("*"), pattern.LastIndexOf("?"));
    var endsWith = pattern.Length > lastWildIndex ? pattern.Substring(lastWildIndex + 1) : pattern;
    if(!lastWildIsHook)
        return Directory.GetFiles(path, pattern).Where(p => p.EndsWith(endsWith)).ToArray();
    else
        return Directory.GetFiles(path, pattern).Where(p => p.EndsWith(endsWith) || p.Substring(0, p.Length - 1).EndsWith(endsWith)).ToArray();
}

难道你不能只添加一个if并检查文件名的最后四个字符吗?

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);
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM