Exact file extension match with GetFiles()?

前端 未结 8 757
温柔的废话
温柔的废话 2020-12-11 04:55

I\'d like to retrieve a list of files whose extensions match a specified string exactly.

DirectoryInfo di = new DirectoryInfo(someValidPath);
List

        
相关标签:
8条回答
  • 2020-12-11 05:14

    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.

    0 讨论(0)
  • 2020-12-11 05:20

    Couldn't you just add an if and check the last four characters of the filename?

    0 讨论(0)
  • 2020-12-11 05:22

    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);
                }
    
    0 讨论(0)
  • 2020-12-11 05:23
    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);
    }
    
    0 讨论(0)
  • 2020-12-11 05:26

    Regex might be overkill. Use the extension on FileInfo.

    foreach (FileInfo fi in di.GetFiles("*.txt").Where(f => f.Extension == ".txt"))
    {
         myFiles.Add(fi);
    } 
    
    0 讨论(0)
  • 2020-12-11 05:27

    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();
    
    0 讨论(0)
提交回复
热议问题