content type by extension

mrblah picture mrblah · Dec 15, 2009 · Viewed 18.6k times · Source

Is there any built in function that returns the content type based on the file extension?

Answer

CesarGon picture CesarGon · Dec 15, 2009

Not that I know of. But you can use this code:

using Microsoft.Win32;

RegistryKey key = Registry.ClassesRoot.OpenSubKey(extension);
string contentType = key.GetValue("Content Type").ToString();

You'll need to add extra code for error handling.

Note: The extension needs to be prefixed by a dot, like in .txt.