如何从文件扩展名中获得MIME类型?


当前回答

您可以在注册表中找到这些信息。例如,.pdf文件的MIME类型可以在键HKEY_CLASSES_ROOT\.pdf中找到,在值"Content type "中:

string mimeType = Registry.GetValue(@"HKEY_CLASSES_ROOT\.pdf", "Content Type", null) as string;

其他回答

受到塞缪尔回答的启发,我写了一个改进版本:

当扩展名是大写时也适用。 以文件名为输入,优雅地处理没有扩展名的文件。 不要在键中包含“。”。 列表,为此我编写了一个小型转换脚本。

最终的源代码超过30K个字符,所以我不能张贴在这里,在Github上检查它。

为了让Shimmy的回答更清楚:

var mimeType = MimeMapping.GetMimeMapping(fileName);

System.Web.dll v4.5开发

// Summary:
//     Returns the MIME mapping for the specified file name.
//
// Parameters:
//   fileName:
//     The file name that is used to determine the MIME type.
public static string GetMimeMapping(string fileName);

由文件扩展名计算的mime类型不一定总是正确的。

让我们说,我可以保存一个文件的。png扩展名,但文件格式,我可以设置为“ImageFormat.jpeg”。

所以在这种情况下,你要计算的文件会给出不同的结果…这可能会导致文件比原始文件大。

如果你正在处理图像,那么你可以使用imagecodecInfo和ImageFormat。

大多数解决方案都在工作,但为什么要这么努力,而我们也可以很容易地获得mime类型。 在系统。Web程序集,有从文件名获取mime类型的方法。 例如:

string mimeType = MimeMapping.GetMimeMapping(filename);

.NET Core获取MimeType的方法:

添加依赖关系

Microsoft.AspNetCore.StaticFiles

private string GetMimeType(string fileName)
{
    var provider = new FileExtensionContentTypeProvider();
    if (!provider.TryGetContentType(fileName, out var contentType))
    {
        contentType = "application/octet-stream";
    }
    return contentType;            
}