在C#中设置MimeType

aca*_*dia 11 c#

有没有一种更好的方法来设置C#中的mimetypes而不是我想要提前感谢的那种.

static String MimeType(string filePath)
{
  String ret = null;
  FileInfo file = new FileInfo(filePath);

  if (file.Extension.ToUpper() == ".PDF")
  {
    ret = "application/pdf";
  }
  else if (file.Extension.ToUpper() == ".JPG" || file.Extension.ToUpper() == ".JPEG")
  {
    ret = "image/jpeg";
  }
  else if (file.Extension.ToUpper() == ".PNG")
  {
    ret = "image/png";
  }
  else if (file.Extension.ToUpper() == ".GIF")
  {
    ret = "image/gif";
  }
  else if (file.Extension.ToUpper() == ".TIFF" || file.Extension.ToUpper() == ".TIF")
  {
    ret = "image/tiff";
  }
  else
  {
    ret = "image/" + file.Extension.Replace(".", "");
  }

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

Voo*_*ild 15

我从这篇博文中得到了这个:

private string GetMimeType (string fileName)
{
    string mimeType = "application/unknown";
    string ext = System.IO.Path.GetExtension(fileName).ToLower();
    Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
    if (regKey != null && regKey.GetValue("Content Type") != null)
    mimeType = regKey.GetValue("Content Type").ToString();
    return mimeType;
}
Run Code Online (Sandbox Code Playgroud)

  • 我打算建议注册表.但是,如果您在部分信任模式下运行,我认为您需要明确授予注册表访问权限,否则它将被拒绝.我可能也会在你的应用程序中缓存请求,而不是每次查询,但更多的是从一般的不安呼叫到注册表而不是硬数据.也许还值得指出:如果没有注册表内容类型,IIS将拒绝提供文件. (2认同)

abz*_*rak 11

只需要这一行就可以做到这一点.

System.Web.MimeMapping.GetMimeMapping(FileName)
Run Code Online (Sandbox Code Playgroud)

注意:这是.NET 4.5+唯一的


gim*_*mel 7

ADictionary<String,String>可能更清楚。

private static Dictionary<String, String> mtypes = new Dictionary<string, string> {
        {".PDF", "application/pdf" },
        {".JPG", "image/jpeg"},
        {".PNG", "image/png"},
        {".GIF", "image/gif"},
        {".TIFF","image/tiff"},
        {".TIF", "image/tiff"}
    };

static String MimeType(String filePath)
{
    System.IO.FileInfo file = new System.IO.FileInfo(filePath);
    String filetype = file.Extension.ToUpper();
    if(mtypes.Keys.Contains<String>(filetype))
        return mtypes[filetype];
    return "image/" + filetype.Replace(".", "").ToLower();
}
Run Code Online (Sandbox Code Playgroud)