Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting MimeType in C#

Tags:

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" || 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;
}
like image 282
acadia Avatar asked Jun 24 '10 16:06

acadia


4 Answers

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();
}
like image 170
gimel Avatar answered Sep 18 '22 19:09

gimel


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.

like image 20
Wim Avatar answered Sep 18 '22 19:09

Wim


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;
}
like image 34
VoodooChild Avatar answered Sep 20 '22 19:09

VoodooChild


Just this one line is needed to do this.

System.Web.MimeMapping.GetMimeMapping(FileName)

Note: It's .NET 4.5+ only

like image 37
abzarak Avatar answered Sep 19 '22 19:09

abzarak