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 "";
}