有没有一种更好的方法来设置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)
abz*_*rak 11
只需要这一行就可以做到这一点.
System.Web.MimeMapping.GetMimeMapping(FileName)
Run Code Online (Sandbox Code Playgroud)
注意:这是.NET 4.5+唯一的
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)