Exact file extension match with GetFiles()?

前端 未结 8 758
温柔的废话
温柔的废话 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:28

    Try this:

    DirectoryInfo di = new DirectoryInfo(someValidPath); 
    List<FileInfo> myFiles =  
        (
            from file in di.GetFiles("*.txt")
            where file.Extension == ".txt"
            select file
        ).ToList();
    
    0 讨论(0)
  • 2020-12-11 05:37

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