如何从文件扩展名中获得MIME类型?
当前回答
您可以在注册表中找到这些信息。例如,.pdf文件的MIME类型可以在键HKEY_CLASSES_ROOT\.pdf中找到,在值"Content type "中:
string mimeType = Registry.GetValue(@"HKEY_CLASSES_ROOT\.pdf", "Content Type", null) as string;
其他回答
受到塞缪尔回答的启发,我写了一个改进版本:
当扩展名是大写时也适用。 以文件名为输入,优雅地处理没有扩展名的文件。 不要在键中包含“。”。 列表,为此我编写了一个小型转换脚本。
最终的源代码超过30K个字符,所以我不能张贴在这里,在Github上检查它。
为了让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);
由文件扩展名计算的mime类型不一定总是正确的。
让我们说,我可以保存一个文件的。png扩展名,但文件格式,我可以设置为“ImageFormat.jpeg”。
所以在这种情况下,你要计算的文件会给出不同的结果…这可能会导致文件比原始文件大。
如果你正在处理图像,那么你可以使用imagecodecInfo和ImageFormat。
大多数解决方案都在工作,但为什么要这么努力,而我们也可以很容易地获得mime类型。 在系统。Web程序集,有从文件名获取mime类型的方法。 例如:
string mimeType = MimeMapping.GetMimeMapping(filename);
.NET Core获取MimeType的方法:
添加依赖关系
Microsoft.AspNetCore.StaticFiles
private string GetMimeType(string fileName)
{
var provider = new FileExtensionContentTypeProvider();
if (!provider.TryGetContentType(fileName, out var contentType))
{
contentType = "application/octet-stream";
}
return contentType;
}
推荐文章
- ASP是什么?NET Identity的IUserSecurityStampStore<TUser>接口?
- net HttpClient。如何POST字符串值?
- 我如何使一个方法的返回类型泛型?
- 何时处理CancellationTokenSource?
- ASP。网网络。config: configSource vs.文件属性
- 如何获取正在执行的程序集版本?
- AutoMapper vs valueinjector
- 为什么控制台不。Writeline,控制台。在Visual Studio Express中编写工作?
- 什么是.NET程序集?
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- 函数应该返回空对象还是空对象?
- 如何转换日期时间?将日期时间
- 如何在c#中连接列表?
- 在c#中引用类型变量的“ref”的用途是什么?
- 防止在ASP中缓存。NET MVC中使用属性的特定操作