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.
  1. public static string GetMimeTypeFromExtension(string extension)
  2. {
  3. string mimeType = string.Empty;
  4. RegistryKey key;
  5. object value;
  6. if (!string.IsNullOrEmpty(extension))
  7. {
  8. if (!extension.StartsWith("."))
  9. {
  10. extension = "." + extension;
  11. }
  12. key = Registry.ClassesRoot.OpenSubKey(extension, false);
  13. value = key != null ? key.GetValue("Content Type", null) : null;
  14. mimeType = value != null ? value.ToString() : string.Empty;
  15. }
  16. return mimeType;
  17. }
While calling you can pass the parameter like,
 " .pdf "
Or
"  pdf  "

our code will handle the dot !.

No comments:

Post a Comment