0

Is there a way to get files by generic mime types?

Example: For all the images ("image/png, image/jpeg, ..."):

DirectoryInfo.GetFiles("image")
pilavust
  • 518
  • 1
  • 7
  • 19

4 Answers4

2

For compatibility reasons, you're best off including the file types yourself in an array, eg.

string[] imagemime = new []{".jpg", ".gif", ".png", ".bmp", ".jpe", ".jpeg", ".wmf", ".emf", ".xbm", ".ico", ".eps", ".tif", ".tiff", ".g01", ".g02", ".g03", ".g04", ".g05", ".g06", ".g07", ".g08"};

Then you could have a method like this:

private static IEnumerable<string> GetFiles(string sourceFolder, string[] exts, System.IO.SearchOption searchOption)
    {
        return System.IO.Directory.GetFiles(sourceFolder, "*.*", searchOption)
                .Where(s=>exts.Contains(System.IO.Path.GetExtension(s), StringComparer.OrdinalIgnoreCase));
    }

You can see a comparison of the performance with other alternatives here.

Chibueze Opata
  • 9,358
  • 7
  • 37
  • 64
1

Not easily. DirectoryInfo goes against the file system, which doesn't inherently contain MIME type information.

You could get all the files by extension using GetFiles() and the extension. You could also hit HKEY_CLASSES_ROOT\MIME\Database\Content Type registry key to turn a list of MIME types into a list of extensions.

MNGwinn
  • 2,334
  • 17
  • 18
0

I'm not sure, but do you mean Directory.GetFiles? If so, you can search for specific file formats like:

Directory.GetFiles(filepath, ".png");
Directory.GetFiles(filepath, ".jpeg");
// etc...

The extensions would be a clear give away of the MIME type.

Eric
  • 1,346
  • 2
  • 14
  • 24
  • The extensions *could* be a clue to the MIME type. However, there is no guarentee that the extension is telling the truth about the contents of a file. – Wonko the Sane Jul 05 '12 at 19:29
  • fair enough. haha. Since he's checking a directory on his computer/server, I'd assume the extension would most likely be telling the truth. However, that is a very valid point you got there. – Eric Jul 05 '12 at 19:48
  • 1
    Just wondering where in his question it says anything about it being only on his computer. :) – Wonko the Sane Jul 05 '12 at 19:52
  • 1
    fine fine. you got me LOL. +1 – Eric Jul 05 '12 at 19:57
0

The DirectoryInfo.GetFiles Method allows to put searchpattern of with wild character such as ? and *

So the DirectoryInfo.GetFiles does not have any options to get files by mime type

But you can use UrlMon for it look at this post for example : Using .NET, how can you find the mime type of a file based on the file signature not the extension

Community
  • 1
  • 1
HatSoft
  • 10,683
  • 3
  • 25
  • 43