Thursday, September 11, 2014

Get MIME Content Type From Extensions C#

I have seen most of the people hard coding the MIME Content Type as a Constant or List to use it in their code. It's not possible to hard code all MIME Content types and use it. So here is a simple code to get those MIME Content type from the System itself based on the extension you are giving.
public static string GetMimeTypeFromExtension(string extension)
{
   string mimeType = string.Empty;
   RegistryKey key;
   object value;
   if (!string.IsNullOrEmpty(extension))
   {
      if (!extension.StartsWith("."))
      {
      extension = "." + extension;
      }
key = Registry.ClassesRoot.OpenSubKey(extension, false); value = key != null ? key.GetValue("Content Type", null) : null; mimeType = value != null ? value.ToString() : string.Empty; }
return mimeType; }
While calling you can pass the parameter like,
 " .pdf "
Or
"  pdf  "

our code will handle the dot !.

No comments:

Post a Comment