views:

81

answers:

6
+1  A: 

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

Shekhar
A: 

you can try something like this:

 var query = from p in Directory.GetFiles(@"C:\").AsEnumerable()
                    where p.Contains(".c")
                    || p.Contains(".h")
                    select p;
anishmarokey
No reason to call AsEnumerable here. GetFiles will have already filled the entire array.
Josh Einstein
+1  A: 

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;
Dan Tao
Only .Net 3.5 :)
Yuriy
@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.
Jeff M
@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.
Dan Tao
@Dan: 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.
Jeff M
@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.
Dan Tao
A: 

See How to get files with multiple extensions using extension methods.

Danny Chen
A: 

Here's some useful helper functions to simulate having multiple filters:

// .NET 4.0 friendly
public static IEnumerable<string> EnumerateFiles(string path, params string[] filters)
{
    return filters.Length == 0
        ? Directory.EnumerateFiles(path)
        : filters.SelectMany(filter => Directory.EnumerateFiles(path, filter));
}

// .NET 3.5 friendly
public static IEnumerable<string> GetFiles(string path, params string[] filters)
{
    return filters.Length == 0
        ? Directory.GetFiles(path)
        : filters.SelectMany(filter => Directory.GetFiles(path, filter));
}
Jeff M
A: 

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

Bear Monkey