如何从文件扩展名中获得MIME类型?


当前回答

. net框架提供了获取mime类型的内置方法。不需要编写自定义代码。

string mimeType = System.Web.MimeMapping.GetMimeMapping(fileName);

其他回答

为了使这篇文章更全面,对于。net核心开发人员有FileExtensionContentTypeProvider类,它涵盖了官方的MIME内容类型。

它在幕后工作——根据文件扩展名在Http响应头中设置ContentType。

如果您需要特殊的MIME类型,请参阅自定义MIME类型的示例:

public void Configure(IApplicationBuilder app)
{
    // Set up custom content types -associating file extension to MIME type
    var provider = new FileExtensionContentTypeProvider();
    // Add new mappings
    provider.Mappings[".myapp"] = "application/x-msdownload";
    provider.Mappings[".htm3"] = "text/html";
    provider.Mappings[".image"] = "image/png";
    // Replace an existing mapping
    provider.Mappings[".rtf"] = "application/x-msdownload";
    // Remove MP4 videos.
    provider.Mappings.Remove(".mp4");

    app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
        RequestPath = new PathString("/MyImages"),
        ContentTypeProvider = provider
    });

    app.UseDirectoryBrowser(new DirectoryBrowserOptions()
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
        RequestPath = new PathString("/MyImages")
    });
}

我已经编写了一个程序来获取和转换Apache mime。类型文件到c#字典<字符串,字符串>的关键文件扩展名。这里的。

实际的输出是这个文件(但是您可能希望获取它并再次运行它,以防Apache文件在我上次运行之后已经更新)。

public static Dictionary<string, string> MimeTypes = new Dictionary<string, string>
{
  { "123", "application/vnd.lotus-1-2-3" },
  { "3dml", "text/vnd.in3d.3dml" },
  { "3g2", "video/3gpp2" },
  { "3gp", "video/3gpp" },
  { "7z", "application/x-7z-compressed" },
  { "aab", "application/x-authorware-bin" },
  { "aac", "audio/x-aac" },
  { "aam", "application/x-authorware-map" },
  { "aas", "application/x-authorware-seg" },
  { "abw", "application/x-abiword" },
  ...

当然,为了将通用完整性、动态性和可移植性的优势与最小的依赖性结合起来

你将结合Samuel Neff的静态字典与特定平台的查询,例如由Bryan Denny。

例如,在Linux下,命令行工具“xdg-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或其他

在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)