存在MimeMapping.GetMimeMapping(string filename)
MimeMapping.GetMimeMapping的對面?
是否存在.Net函數,即「相反」。這需要一個MIME字符串並返回文件類型擴展名?
存在MimeMapping.GetMimeMapping(string filename)
MimeMapping.GetMimeMapping的對面?
是否存在.Net函數,即「相反」。這需要一個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"]));
有正好碰上這個自己和不高興具有(通過提供一個備用名單什麼MimeMapping
使用)GetMimeMapping
和反向之間的不匹配,我挖成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;
}
我決定不扔在反思失敗的情況例外,只是不返回擴展,因爲它符合我個人的使用情況。
當我在我的系統上使用「image/jpeg」時,它會返回.jfif,.jpeg和.jpg。任何想法如何可以區分.jpg將是我的首選擴展?我查看了註冊表,但沒有找到任何可以使用的內容... – Jeff