Can you call Directory.GetFiles() with multiple filters?

前端 未结 26 2784
逝去的感伤
逝去的感伤 2020-11-22 05:25

I am trying to use the Directory.GetFiles() method to retrieve a list of files of multiple types, such as mp3\'s and jpg\'s. I have t

26条回答
  •  执念已碎
    2020-11-22 06:10

    for

    var exts = new[] { "mp3", "jpg" };
    

    You could:

    public IEnumerable FilterFiles(string path, params string[] exts) {
        return
            Directory
            .EnumerateFiles(path, "*.*")
            .Where(file => exts.Any(x => file.EndsWith(x, StringComparison.OrdinalIgnoreCase)));
    }
    
    • Don't forget the new .NET4 Directory.EnumerateFiles for a performance boost (What is the difference between Directory.EnumerateFiles vs Directory.GetFiles?)
    • "IgnoreCase" should be faster than "ToLower" (.EndsWith("aspx", StringComparison.OrdinalIgnoreCase) rather than .ToLower().EndsWith("aspx"))

    But the real benefit of EnumerateFiles shows up when you split up the filters and merge the results:

    public IEnumerable FilterFiles(string path, params string[] exts) {
        return 
            exts.Select(x => "*." + x) // turn into globs
            .SelectMany(x => 
                Directory.EnumerateFiles(path, x)
                );
    }
    

    It gets a bit faster if you don't have to turn them into globs (i.e. exts = new[] {"*.mp3", "*.jpg"} already).

    Performance evaluation based on the following LinqPad test (note: Perf just repeats the delegate 10000 times) https://gist.github.com/zaus/7454021

    ( reposted and extended from 'duplicate' since that question specifically requested no LINQ: Multiple file-extensions searchPattern for System.IO.Directory.GetFiles )

提交回复
热议问题