如何从文件扩展名中获得MIME类型?
当前回答
受到塞缪尔回答的启发,我写了一个改进版本:
当扩展名是大写时也适用。 以文件名为输入,优雅地处理没有扩展名的文件。 不要在键中包含“。”。 列表,为此我编写了一个小型转换脚本。
最终的源代码超过30K个字符,所以我不能张贴在这里,在Github上检查它。
其他回答
我对这些mimetypes的理解,使用apache列表,下面的脚本将为您提供一个包含所有mimetypes的字典。
var mimeTypeListUrl = "http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types";
var webClient = new WebClient();
var rawData = webClient.DownloadString(mimeTypeListUrl).Split(new[] { Environment.NewLine, "\n" }, StringSplitOptions.RemoveEmptyEntries);
var extensionToMimeType = new Dictionary<string, string>();
var mimeTypeToExtension = new Dictionary<string, string[]>();
foreach (var row in rawData)
{
if (row.StartsWith("#")) continue;
var rowData = row.Split(new[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
if (rowData.Length != 2) continue;
var extensions = rowData[1].Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
if (!mimeTypeToExtension.ContainsKey(rowData[0]))
{
mimeTypeToExtension.Add(rowData[0], extensions);
}
foreach (var extension in extensions)
{
if (!extensionToMimeType.ContainsKey(extension))
{
extensionToMimeType.Add(extension, rowData[0]);
}
}
}
如果你不想增加额外的依赖关系,并且仍然想要版本独立的请求,你可以把这个关于如何在不同的。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。
使用MimeTypeMap包,它提供了文件扩展名到mime类型以及mime类型到文件扩展名的巨大双向映射
使用mimetype;
获取扩展的mime类型
Console.WriteLine("txt -> " + MimeTypeMap.GetMimeType("txt")); // "text/plain"
获取mime类型的扩展名
Console.WriteLine("audio/wav -> " + MimeTypeMap.GetExtension("audio/wav")); // ".wav"
GitHub网址:https://github.com/samuelneff/MimeTypeMap
您可以使用Apache的httpd提供的表。将其映射到函数、字典、列表等应该是很简单的。
另外,正如这里所看到的,extension->mime类型不一定是函数。每个文件扩展名可能有多种常见的MIME类型,所以你应该看看你的应用程序的需求,看看你为什么关心MIME类型,你想用它们“做什么”等等。您可以使用文件扩展名来确定相同的行为吗?您是否也需要读取文件的前几个字节来确定其MIME类型?
Bryan Denny上面的帖子不适合我,因为不是所有的扩展在注册表中都有一个“内容类型”子键。我不得不调整代码如下:
private string GetMimeType(string sFileName)
{
// Get file extension and if it is empty, return unknown
string sExt = Path.GetExtension(sFileName);
if (string.IsNullOrEmpty(sExt)) return "Unknown file type";
// Default type is "EXT File"
string mimeType = string.Format("{0} File", sExt.ToUpper().Replace(".", ""));
// Open the registry key for the extension under HKEY_CLASSES_ROOT and return default if it doesn't exist
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(sExt);
if (regKey == null) return mimeType;
// Get the "(Default)" value and re-open the key for that value
string sSubType = regKey.GetValue("").ToString();
regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(sSubType);
// If it exists, get the "(Default)" value of the new key
if (regKey?.GetValue("") != null) mimeType = regKey.GetValue("").ToString();
// Return the value
return mimeType;
}
现在它可以为我所有注册的文件类型和未注册的或通用的文件类型(如JPG等)。
推荐文章
- 最好的方法在asp.net强制https为整个网站?
- 在ASP .NET身份声明是什么
- 将字符串转换为System.IO.Stream
- 如何从枚举中选择一个随机值?
- 驻留在App_Code中的类不可访问
- 在链式LINQ扩展方法调用中等价于'let'关键字的代码
- dynamic (c# 4)和var之间的区别是什么?
- Visual Studio: ContextSwitchDeadlock
- 返回文件在ASP。Net Core Web API
- 自定义HttpClient请求头
- 无法启动IIS Express Web服务器,注册URL失败,访问被拒绝
- 如果我使用OWIN Startup.cs类并将所有配置移动到那里,我是否需要一个Global.asax.cs文件?
- ASP。NET Identity DbContext混淆
- VS2013外部构建错误"error MSB4019: The imported project <path> was not found"
- 从另一个列表id中排序一个列表