Snippet: Mime types and file extensions

If you have a mime type and you want to find the default extension for it, you can get this from the Extension value in the following registry key:

text
HKEY_CLASSES_ROOT\MIME\Database\Content Type\<mime type>
csharp
public static string GetDefaultExtension(string mimeType)
{
  string result;
  RegistryKey key;
  object value;

  key = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type\" + mimeType, false);
  value = key != null ? key.GetValue("Extension", null) : null;
  result = value != null ? value.ToString() : string.Empty;

  return result;
}

One the other hand, if you have a file extension and you want to know what that mime type is, you can get that via the Content Type value of this key:

text
HKEY_CLASSES_ROOT\<extension>
csharp
public static string GetMimeTypeFromExtension(string extension)
{
  string result;
  RegistryKey key;
  object value;

  if (!extension.StartsWith("."))
    extension = "." + extension;

  key = Registry.ClassesRoot.OpenSubKey(extension, false);
  value = key != null ? key.GetValue("Content Type", null) : null;
  result = value != null ? value.ToString() : string.Empty;

  return result;
}

Update History

  • 2010-04-04 - First published
  • 2020-11-21 - Updated formatting

Like what you're reading? Perhaps you like to buy us a coffee?

Donate via Buy Me a Coffee

Donate via PayPal


Comments

We'll never share your email with anyone else Styling with Markdown is supported