Get files from directory with pattern

21,884

Solution 1

its not possible to specify multiple filters in single GetFiles() method call. You can find alternatives here

Solution 2

If you're using .NET 4.0, I'd go with Directory.EnumerateFiles:

var files = from f in Directory.EnumerateFiles("C:\\")
            where f.EndsWith(".c") || f.EndsWith(".h")
            select f;

Solution 3

For .Net 3.5.

public IEnumerable<string> GetFiles(
     string basePath, 
     params string[] searchPatterns)
{
    if (searchPatterns == null || searchPatterns.Length == 0)
    {
        return Directory.GetFiles(basePath);
    }

    return Enumerable.SelectMany(searchPatterns, 
                         p => Directory.GetFiles(basePath, p));
}

Usage:

GetFiles(@"c:\", "*.c", "*.h");

you probably want to add some validation

Solution 4

you can try something like this:

 var query = from p in Directory.GetFiles(@"C:\").AsEnumerable()
                    where p.Contains(".c")
                    || p.Contains(".h")
                    select p;
Share:
21,884
Yuriy
Author by

Yuriy

.Net Developer. My motto is Nothing is impossible..

Updated on September 23, 2020

Comments

  • Yuriy
    Yuriy over 3 years

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

    Does it possible to get for ex. .c and .hfiles from directory. Usage of Directory.GetFiles("C:\", ".c;.h"); does not work. It's too bad to invoke Directory.GetFiles(...); twice.. :(

    Thanks.

  • Jeff Mercado
    Jeff Mercado over 13 years
    @Yuriy: The only thing .NET 4.0 there is the use of Directory.EnumerateFiles(). Change it to Directory.GetFiles() and it should work just as fine.
  • Dan Tao
    Dan Tao over 13 years
    @Jeff M: I could be wrong, but I'm pretty sure @Yuriy wants to avoid calling GetFiles() to dodge the cost of populating a (potentially) huge string[] array.
  • Josh
    Josh over 13 years
    No reason to call AsEnumerable here. GetFiles will have already filled the entire array.
  • Jeff Mercado
    Jeff Mercado over 13 years
    If that were the case, then getting all files then filtering wouldn't be the best way to handle this then. ;) I figured Yuriy would like to apply these filters in a single call rather than writing two separate calls by hand which seems reasonable based on the answer that was chosen.
  • Dan Tao
    Dan Tao over 13 years
    @Jeff: True -- but it'd still be cheaper (memory-wise) than GetFiles(), and would start returning values right away (without having to fetch all files first). But you're right; judging from the accepted answer, it seems the OP wasn't too concerned about that, actually.