【发布时间】:2014-02-15 06:48:08
【问题描述】:
存在MimeMapping.GetMimeMapping(string filename)
是否存在一个 .Net 函数,它是“相反的”。这需要一个 mime 字符串并返回文件类型扩展名?
【问题讨论】:
标签: c# mime-types mime
存在MimeMapping.GetMimeMapping(string filename)
是否存在一个 .Net 函数,它是“相反的”。这需要一个 mime 字符串并返回文件类型扩展名?
【问题讨论】:
标签: c# mime-types mime
您可以阅读注册表以获取该信息。
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"]));
【讨论】:
我自己刚刚遇到这个问题并且对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;
}
我决定在反射失败的情况下不抛出异常,并且不返回任何扩展,因为它符合我的个人用例。
【讨论】: