开发者

Finding a MIME type for a file on windows

开发者 https://www.devze.com 2022-12-24 23:39 出处:网络
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 function

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 w开发者_如何学Goork 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!


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


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.


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消