在 Windows 上查找文件的 MIME 类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2549015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 14:12:28  来源:igfitidea点击:

Finding a MIME type for a file on windows

c++windowsmime-types

提问by rmeador

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).

有没有办法在 Windows 上使用一些系统调用来获取文件的 MIME 类型?我正在用 C++ 编写一个 IIS 扩展,所以它必须可以从 C++ 调用,如果有一些功能公开,我确实可以访问 IIS。显然,IIS 本身必须能够做到这一点,但我的谷歌搜索一直无法找到方法。我确实在 SO 上找到了这个与 .net 相关的问题,但这并没有给我太多希望(因为那里既没有提到好的解决方案也没有提到 C++ 解决方案)。

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!

我需要它,以便我可以使用我的应用程序中的适当内容类型提供动态文件。我的计划是首先查阅我的应用程序中的 MIME 类型列表,然后返回到系统的 MIME 类型列表(但是这可行;显然它存在,因为它是您将文件与程序关联的方式)。在某些情况下,我只有一个文件扩展名可以使用,但在其他情况下,我可能需要检查一个实际的磁盘文件。由于这些不是用户上传的文件,我相信我可以信任扩展名,我更喜欢仅扩展名的查找解决方案,因为它看起来更简单、更快。谢谢!

回答by Jerry Coffin

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

HKCR\\.<ext>\Content Type(其中“ext”是文件扩展名)通常保存 MIME 类型。

回答by Peter Tseng

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

粘贴自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;
}

回答by Roger Cook

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

在 Windows 10 中,不同的 MIME 类型存储在注册表中:

HKEY_CLASSES_ROOT\MIME\Database\Content Type

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

在该键下为每种内容类型(例如text/plain)提供一个键。