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


当前回答

如果你不想增加额外的依赖关系,并且仍然想要版本独立的请求,你可以把这个关于如何在不同的。net版本中获得MIME-Type的答案与这个关于多个。net框架版本的条件构建的答案混合在一起。

我做的第一件事是编辑我的项目文件。在最后一个构建定义之后,我添加了第二个答案中所述的属性组:

<PropertyGroup>
    <DefineConstants Condition=" !$(DefineConstants.Contains(';NET')) ">$(DefineConstants);$(TargetFrameworkVersion.Replace("v", "NET").Replace(".", ""))</DefineConstants>
    <DefineConstants Condition=" $(DefineConstants.Contains(';NET')) ">$(DefineConstants.Remove($(DefineConstants.LastIndexOf(";NET"))));$(TargetFrameworkVersion.Replace("v", "NET").Replace(".", ""))</DefineConstants>
</PropertyGroup>

现在我为MimeExtensionHelper提供了一个与第一个答案不同的实现,并为所有来自。net 4.5或更高版本的客户端提供了一个额外的实现,只需调用System.Web.MimeMapping.GetMimeMapping:

#if (NET10 || NET11 || NET20 || NET30 || NET35)
public static class MimeExtensionHelper
{
    static object locker = new object();
    static MethodInfo getMimeMappingMethodInfo;

    static MimeExtensionHelper()
    {
        Type mimeMappingType = Assembly.GetAssembly(typeof(HttpRuntime)).GetType("System.Web.MimeMapping");

        if (mimeMappingType == null)
            throw new SystemException("Couldnt find MimeMapping type");

        ConstructorInfo constructorInfo = mimeMappingType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);

        if (constructorInfo == null)
            throw new SystemException("Couldnt find default constructor for MimeMapping");

        mimeMapping = constructorInfo.Invoke(null);

        if (mimeMapping == null)
            throw new SystemException("Couldnt find MimeMapping");

        getMimeMappingMethodInfo = mimeMappingType.GetMethod("GetMimeMapping", BindingFlags.Static | BindingFlags.NonPublic);

        if (getMimeMappingMethodInfo == null)
            throw new SystemException("Couldnt find GetMimeMapping method");

        if (getMimeMappingMethodInfo.ReturnType != typeof(string))
            throw new SystemException("GetMimeMapping method has invalid return type");

        if (getMimeMappingMethodInfo.GetParameters().Length != 1 && getMimeMappingMethodInfo.GetParameters()[0].ParameterType != typeof(string))
            throw new SystemException("GetMimeMapping method has invalid parameters");
    }

    public static string GetMimeType(string fileName)
    {
        lock (locker)
        {
            return (string)getMimeMappingMethodInfo.Invoke(null, new object[] { fileName });
        }
    }
}
#elif NET40
public static class MimeExtensionHelper
{
    static object locker = new object();
    static MethodInfo getMimeMappingMethodInfo;

    static MimeExtensionHelper()
    {
        Type mimeMappingType = Assembly.GetAssembly(typeof(HttpRuntime)).GetType("System.Web.MimeMapping");

        if (mimeMappingType == null)
            throw new SystemException("Couldnt find MimeMapping type");           

        getMimeMappingMethodInfo = mimeMappingType.GetMethod("GetMimeMapping", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

        if (getMimeMappingMethodInfo == null)
            throw new SystemException("Couldnt find GetMimeMapping method");

        if (getMimeMappingMethodInfo.ReturnType != typeof(string))
            throw new SystemException("GetMimeMapping method has invalid return type");

        if (getMimeMappingMethodInfo.GetParameters().Length != 1 && getMimeMappingMethodInfo.GetParameters()[0].ParameterType != typeof(string))
            throw new SystemException("GetMimeMapping method has invalid parameters");
    }

    public static string GetMimeType(string fileName)
    {
        lock (locker)
        {
            return (string)getMimeMappingMethodInfo.Invoke(null, new object[] { fileName });
        }
    }
}
#else // .NET 4.5 or later
public static class MimeExtensionHelper
{
    public static string GetMimeType(string fileName)
    {
        return MimeMapping.GetMimeMapping(fileName);
    }
}
#endif

同样在。net 4.5之前的版本中,静态MimeMapping类拥有一个名为_mappingDictionary的静态实例(类型为MimeMapping. mimemappingdictionarybase),您可以从反射请求该实例,以便添加可能还不支持的新的MIME-Types。

其他回答

如果有人能在linux上使用libmagic类似的功能,那就更好了,因为我认为这是一种比依赖文件扩展名更好的检测文件类型的方法。

例如,如果我将一个文件从myppicture .jpg重命名为myppicture .txt 在linux上,它仍然会被报告为一张图片 但是在这里使用这种方法,它将被报告为文本文件。

目光Tomas

IANA媒体类型

我希望微软能把他们的行业标准统一起来!对于其他人,有兴趣的人:

离散的类型

application: https://www.iana.org/assignments/media-types/media-types.xhtml#application audio: https://www.iana.org/assignments/media-types/media-types.xhtml#audio example: https://www.iana.org/assignments/media-types/media-types.xhtml#examples font: https://www.iana.org/assignments/media-types/media-types.xhtml#font image: https://www.iana.org/assignments/media-types/media-types.xhtml#image model: https://www.iana.org/assignments/media-types/media-types.xhtml#model text: https://www.iana.org/assignments/media-types/media-types.xhtml#text video: https://www.iana.org/assignments/media-types/media-types.xhtml#video

多部分类型

信息:https://www.iana.org/assignments/media-types/media-types.xhtml消息 多部分:https://www.iana.org/assignments/media-types/media-types.xhtml #多部分

我想推荐一个阅读:MIME类型(IANA媒体类型)的Mozilla页面感兴趣的人!它的信息量很大!

在代码方面,上面的每个链接都有一个.csv文件下载:https://www.iana.org/assignments/media-types/application.csv

正如这里已经指出的,可以使用Dictionary或ConcurrentDictionary下载并使用Key - Value对填充Dictionary。

我已经编译了一个有名的mime类型和内容类型值的来源列表,这些值仅以文件扩展名为键(目前)。

nuget包在这里https://www.nuget.org/packages/FTTLib.dll/

来源在这里https://github.com/brondavies/filetypetranslator/

这个库被设计成:

无外部依赖 没有文件系统访问权限 内存占用小 简单的静态方法(没有扩展方法和可实例化类) 不区分大小写 可移植-工作在应用程序针对任何CLR(。NET 2.0 +)

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

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

你可以使用这个helper函数:

private string GetMimeType (string fileName)
{
    string mimeType = "application/unknown";
    string ext = System.IO.Path.GetExtension(fileName).ToLower();
    Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
    if (regKey != null && regKey.GetValue("Content Type") != null)
    mimeType = regKey.GetValue("Content Type").ToString();
    return mimeType;
}