Retrieving the MIME type of a given extension - Ed's Blog
in

dotnet.org.za

South African .NET Developer Portal

Ed's Blog

Object reference not set to an instance of an object

Retrieving the MIME type of a given extension

I've had to this often on my programming escapades. Usually I created some sort of in memory lookup table, but this time I thought there had to be a better way and it turns out there is. All the MIME types and file extensions are stored in the registry. So all you have to do is loop through the MIME types and search for the extension you're looking for.
Probably not the most high performance solution, but I could not notice the difference between this and the old code.

Here is some code:

public static string getMimeType(string sExtension)

{

    string extension = sExtension.ToLower();

    RegistryKey key = Registry.ClassesRoot.OpenSubKey("MIME\\Database\\Content Type");

    foreach (string keyName in key.GetSubKeyNames())

    {

        RegistryKey temp = key.OpenSubKey(keyName);

        if (extension.Equals(temp.GetValue("Extension")))

        {

            return keyName;

        }

    }

     return "";

}

Published Feb 03 2005, 11:05 AM by eduard
Filed under:

Comments

 

Colin said:

Nice! I have a project that needs this, thanks
February 3, 2005 5:03 PM
 

Les Matheson said:

Although I'm not yet convinced this is the "right" way to do it, the performance will be a lot faster if you directly look up the type based on the extension. Each extension has its own registry key under HKCR/{extension}. For example, HKCR\.pdf has a value named "ContentType" which is "application/pdf". The only reason I hesitate to declare this as the right answer is that the application has to have permissions to read HKCR, which may not always be the case. Seems like there must be an API for this...
September 2, 2005 2:40 AM
 

Vadim Sheremet said:

Very useful! I just used it in my app. Thanks!

September 12, 2007 5:53 PM
 

Riaan said:

It should be easier to reference the MIME-type key directly and catch any errors if the key is not present.

February 4, 2008 9:09 AM
 

Eliott said:

Genius, just what I needed, very useful code thanks.

March 4, 2008 10:04 AM
 

Dennie said:

Thanks. Helped me a lot. :)

June 6, 2008 10:08 AM
 

Anand Parthasarathi said:

Thanks a lot.. that was just what I needed..

December 17, 2008 9:10 AM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add
Powered by Community Server (Commercial Edition), by Telligent Systems