13

Is there a way to get a file's MIME type using some system call on Windows? I'm writing an IIS extension in C++, so it must be callable from C++, and I do have access to IIS if there is some functionality exposed. Obviously, IIS itself must be able to do this, but my googling has been unable to find out how. I did find this .net related question here on SO, but that doesn't give me much hope (as neither a good solution nor a C++ solution is mentioned there).

I need it so I can serve up dynamic files using the appropriate content type from my app. My plan is to first consult a list of MIME types within my app, then fall back to the system's MIME type listing (however that works; obviously it exists since it's how you associate files with programs). I only have a file extension to work with in some cases, but in other cases I may have an actual on-disk file to examine. Since these will not be user-uploaded files, I believe I can trust the extension and I'd prefer an extension-only lookup solution since it seems simpler and faster. Thanks!

Community
  • 1
  • 1
rmeador
  • 25,504
  • 18
  • 62
  • 103
  • Your assumption is incorrect: on Windows, the association between extensions and programs does not use MIME types. In the registry, each extension is associated with a descriptive entry, and that has a `\Shell\Open\Command\ ` value. This indirection allows two extensions to share one descriptive entry, e.g. `.jpeg` and `.jpg` share the descriptive entry `jpegfile` – MSalters Mar 31 '10 at 13:07
  • MSalters, I could swear that in XP, the file association dialog had a place in it for MIME type... but here on Win Server 2k8, in the "Default Programs" dialog, it seems to be just as you say... that is not useful to me :( – rmeador Mar 31 '10 at 15:27

3 Answers3

18

HKEY_CLASSES_ROOT\\.<ext>\Content Type (where "ext" is the file extension) will normally hold the MIME type.

Richie Bendall
  • 7,738
  • 4
  • 38
  • 58
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
1

In Windows 10, the different MIME types are stored in the registry at:

HKEY_CLASSES_ROOT\MIME\Database\Content Type

with a key for each content type (e. g. text/plain) under that key.

Roger Cook
  • 93
  • 6
0

Pasted from http://www.snoyman.com/blog/2012/03/ie-mimetype-png.html:

#include <urlmon.h>
#include <stdio.h>

int main(int argc, char* argv[])
{
    char buff[256];
    LPWSTR out;

    FILE *in = fopen("title.png", "rb");

    fread(buff, 1, 256, in);

    FindMimeFromData(NULL, NULL, buff, 256, NULL, FMFD_DEFAULT, &out, 0);

    printf("%ls\n", out);

    return 0;
}
Peter Tseng
  • 13,613
  • 4
  • 67
  • 57
  • As of December 1 2022, FindMimeTypeFromData() does not know many mime types. It says "application/octect-stream" for almost all files. It is a useless function. – Eric M Dec 01 '22 at 20:12