Possible Duplicate:
GetFiles with multiple extentions

is there a function like GetFiles that takes more then 1 file type like

DirectoryInfo di = new DirectoryInfo("c:/inetpub/wwwroot/demos");
FileInfo[] rgFiles = di.GetFiles("*.bmp, *.jpg, etc");

5 Answers

9
SLaks On Best Solutions

AFAIK, this isn't directly possible.

Instead, you can get every file, then filter the array:

HashSet<string> allowedExtensions = new HashSet<string>(extensionArray, StringComparer.OrdinalIgnoreCase);
FileInfo[] files = Array.FindAll(dirInfo.GetFiles(), f => allowedExtensions.Contains(f.Extension));

extensionArray must include . before each extension, but is case-insensitive.

5
Codesleuth On

Not that I know of. I implemented the same problem like so:

DirectoryInfo di = new DirectoryInfo("c:/inetpub/wwwroot/demos");
FileInfo[] rgFiles = di.GetFiles("*.bmp")
    .Union(di.GetFiles("*.jpg"))
    .Union(di.GetFiles("etc"))
    .ToArray();

Note that this requires the System.Linq namespace.

0
dexter On

If you want your code to be bullet proof in the sense your file detection mechanism detects an image file not based on the extension but on the nature of the file, you'd have to to load your files as byte[] and look for a magic trail of bytes usually in the beginning of the array. Every graphical file has it's own way of manifesting itself to the software through presenting that magic value of bytes. I can post some code examples if you'd like.

0
Noring On

No, theres not. Windows does not have a way to separate filters in the search pattern. This could be done manually through LINQ, though.

By using the EnumerateFiles you'll get results as they come back so you don't have to wait for all the files in order to start working on the result.

        var directory = new DirectoryInfo("C:\\");
        var allowedExtensions = new string[] { ".jpg", ".bmp" };

        var imageFiles = from file in directory.EnumerateFiles("*", SearchOption.AllDirectories)
                         where allowedExtensions.Contains(file.Extension.ToLower())
                         select file;

        foreach (var file in imageFiles)
            Console.WriteLine(file.FullName);