如何从文件扩展名中获得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等)。
其他回答
为了让Shimmy的回答更清楚:
var mimeType = MimeMapping.GetMimeMapping(fileName);
System.Web.dll v4.5开发
// Summary:
// Returns the MIME mapping for the specified file name.
//
// Parameters:
// fileName:
// The file name that is used to determine the MIME type.
public static string GetMimeMapping(string fileName);
你可以使用这个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;
}
ASP。NET或其他
在ASP中,选项发生了一些变化。NET Core,在这里(学分):
新FileExtensionContentTypeProvider()。TryGetContentType(文件名,输出内容类型);(仅vNext) 从未测试过,但看起来您可以通过公开的Mappings属性正式展开mime类型列表。 使用MimeTypes NuGet包 从.NET Framework的引用源中复制mimemaps文件
对于。net Framework >= 4.5:
使用System.Web.MimeMapping.GetMimeMapping方法,这是.NET Framework 4.5中BCL的一部分:
string mimeType = MimeMapping.GetMimeMapping(fileName);
如果你需要添加自定义映射,你可以使用反射来向BCL MimeMapping类添加映射,它使用一个自定义字典来公开这个方法,所以你应该调用下面的方法来添加映射(从未测试过,但应该问题。工作)。
无论如何,当使用反射来添加MIME类型时,要注意,由于您正在访问私有字段,因此它的名称可能会更改甚至完全被删除,因此您应该格外谨慎,添加双重检查并为每一步提供故障安全操作。
MimeMapping._mappingDictionary.AddMapping(string fileExtension, string mimeType)
如果你不想增加额外的依赖关系,并且仍然想要版本独立的请求,你可以把这个关于如何在不同的。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
推荐文章
- 最好的方法在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中排序一个列表