【问题标题】:Opposite of MimeMapping.GetMimeMapping?与 MimeMapping.GetMimeMapping 相反?
【发布时间】:2014-02-15 06:48:08
【问题描述】:

存在MimeMapping.GetMimeMapping(string filename)

是否存在一个 .Net 函数,它是“相反的”。这需要一个 mime 字符串并返回文件类型扩展名?

【问题讨论】:

    标签: c# mime-types mime


    【解决方案1】:

    您可以阅读注册表以获取该信息。

    var mapping = Microsoft.Win32.Registry.ClassesRoot.GetSubKeyNames()
                   .Select(key => new
                    {
                        Key = key,
                        ContentType = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(key).GetValue("Content Type")
                    })
                    .Where(x => x.ContentType != null)
                    .ToLookup(x => x.ContentType, x => x.Key);
    
    Console.WriteLine(String.Join(";",mapping["image/jpeg"]));
    

    【讨论】:

    • 当我在我的系统上将它用于“image/jpeg”时,它会返回 .jfif、.jpeg 和 .jpg。知道如何区分 .jpg 将是我的首选扩展名吗?我查看了注册表,但没有找到可以使用的任何东西...
    【解决方案2】:

    我自己刚刚遇到这个问题并且对GetMimeMapping 与其反向之间的不匹配感到不满(通过提供MimeMapping 使用的替代列表),我挖掘了MimeMapping 本身以获取其内部映射。

    public static IEnumerable<string> GetExtensions(this string mimeType)
    {
        var mappingDictionaryField = typeof(MimeMapping).GetField("_mappingDictionary", BindingFlags.NonPublic | BindingFlags.Static);
    
        if (mappingDictionaryField == null)
            return new string[0];
    
        // get the internal dictionary used for mime type lookup
        var mappingDictionary = mappingDictionaryField.GetValue(null); 
    
        if (mappingDictionary == null)
            return new string[0];
    
        // get type that owns the populate method and populated dictionary
        var dictionaryType = mappingDictionary.GetType().BaseType;
    
        if (dictionaryType == null)
            return new string[0];
    
        var populateMethod = dictionaryType.GetMethod("PopulateMappings", BindingFlags.NonPublic | BindingFlags.Instance);
    
        if (populateMethod == null)
            return new string[0];
    
        populateMethod.Invoke(mappingDictionary, null); 
    
        // get the populated mapping dictionary
        var mappingField = dictionaryType.GetField("_mappings", BindingFlags.Instance | BindingFlags.NonPublic);
    
        if (mappingField == null)
            return new string[0];
    
        var mapping = mappingField.GetValue(mappingDictionary) as IDictionary<string, string>;
    
        if (mapping == null)
            return new string[0];
    
        var extensions = mapping.Where(x => x.Value == mimeType)
                                .Select(x => x.Key);
    
        return extensions;
    }
    

    我决定在反射失败的情况下不抛出异常,并且不返回任何扩展,因为它符合我的个人用例。

    【讨论】:

      猜你喜欢
      • 2011-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-01
      • 2021-09-17
      • 1970-01-01
      • 2016-11-23
      相关资源
      最近更新 更多