Setting MimeType in C#
Is there a better way of setting mimetypes in C# than the one I am trying to do thanks in advance.
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" 开发者_如何学Go|| 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;
}
I got this from this blogpost:
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;
}
Just this one line is needed to do this.
System.Web.MimeMapping.GetMimeMapping(FileName)
Note: It's .NET 4.5+
only
A Dictionary<String,String>
may prove to be clearer.
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();
}
If you don't have registry access or don't want to use the registry, you could always use a Dictionary for that.
Dictionary<string,string> mimeTypes = new Dictionary<string,string>() {
{ ".PDF","application/pdf"},
{ ".JPG", "image/jpeg" },
{ ".JPEG", "image/jpeg" } }; // and so on
Then use:
string mimeType = mimeTypes[fileExtension];
In addition, you could store these mappings in an XML file and cache them with a file dependency, rather than keeping them in your code.
精彩评论