如何按内容类型获取文件扩展名?
示例我知道该文件是"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)
Mar*_*oth 12
尽管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)
| 归档时间: |
|
| 查看次数: |
19211 次 |
| 最近记录: |