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

PSS*_*Sim 22 c# content-type

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

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

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

    { DETERMINATION CODE IN HERE }

    return ext;
}
Run Code Online (Sandbox Code Playgroud)

Bra*_*ner 31

我所知道的"最佳"解决方案是查询注册表.你可以在这里找到示例代码. 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;
    }
Run Code Online (Sandbox Code Playgroud)

  • 如果您从中获取扩展名的系统可以打开该文件,则此方法有效.对于xls,您需要安装Excel等 (6认同)
  • 您好Bhargav,您可能想尝试Nuget的MediaTypeMap.请参阅链接https://github.com/samuelneff/MimeTypeMap#getting-the-extension-to-a-mime-type.希望你满意 (2认同)

Mar*_*oth 12

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

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

幸运的是,这里有一个很小的NuGet库,它实质上包含官方MIME类型和相应扩展的硬编码映射,而没有任何外部依赖关系https : //github.com/samuelneff/MimeTypeMap。它在NuGet上可以作为MediaTypeMap使用。安装完软件包后,调用过程非常简单:

MimeTypeMap.GetExtension("audio/wav")
Run Code Online (Sandbox Code Playgroud)

将其放入您的示例中,您可以简单地:

private static string GetExtension(string contentType)
{
    return MimeTypes.MimeTypeMap.GetExtension(contentType);
}
Run Code Online (Sandbox Code Playgroud)

  • 一行代码就是我喜欢懒惰开发人员的原因! (5认同)
  • 很棒的东西工作得很好,因为我的 web 应用程序在 Azure 上运行,不能依赖注册表方法 (3认同)