C#按内容类型获取文件扩展名

时间:2014-04-15 15:12:46

标签: c# content-type

如何按内容类型获取文件扩展名?

示例我知道该文件是“text / css”,因此扩展名为“.css”。

private static string GetExtension(string contentType)
{
    string ext = ".";

    { DETERMINATION CODE IN HERE }

    return ext;
}

2 个答案:

答案 0 :(得分:30)

我所知道的“最佳”解决方案是查询注册表。你可以在这里找到示例代码。 http://cyotek.com/blog/mime-types-and-file-extensions

 public static string GetDefaultExtension(string mimeType)
    {
      string result;
      RegistryKey key;
      object value;

      key = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type\" + mimeType, false);
      value = key != null ? key.GetValue("Extension", null) : null;
      result = value != null ? value.ToString() : string.Empty;

      return result;
    }

答案 1 :(得分:1)

[2019] .NET Core / Standard兼容的便携式方式

尽管Bradley的答案在运行.NET Framework的常规旧Windows计算机上仍然是完美的,但是Registry是Windows特定的,并且在将应用程序移植到非Windows环境时将失败

幸运的是,这里有一个很小的NuGet库,其中基本上包含官方MIME类型和相应扩展名的硬编码映射,没有任何外部依赖性,这里:https://github.com/samuelneff/MimeTypeMap。在NuGet上以MediaTypeMap的形式提供。安装软件包后,调用就很简单:

MimeTypeMap.GetExtension("audio/wav")

要将其放入您的示例中,您只需:

private static string GetExtension(string contentType)
{
    return MimeTypes.MimeTypeMap.GetExtension(contentType);
}
相关问题