How to get the Content Type (MimeType) of a file in C#

Method 1: Using the Registry

This is the most common example found on the web. It uses the registry to get the content type. But there is one big drawback with this approach. Registry has content types stored only for the applications installed on the system. For example, if you need to get content type for mydocument.docx and Word 2007 is not installed, this method will fail.

public string GetContentType(string fname)
{
// set a default mimetype if not found.
string contentType = "application/octet-stream";

try
{
// get the registry classes root
RegistryKey classes = Registry.ClassesRoot;

// find the sub key based on the file extension
RegistryKey fileClass = classes.OpenSubKey(Path.GetExtension(fname));
contentType = fileClass.GetValue("Content Type").ToString();
}
catch { }

return contentType;
}

Method 2: Store the mapping in a configuration file

You can create a custom configuration section in web.config to easily store the mapping between a file extension and content type. The Configuration API build into ASP.NET provides rich support for the addition of your own custom configuration sections.

Here's one example how we can create a configuration section like below -



Start with a MimeTypesSectionHandler class that inherits from System.Configuration.ConfigurationSection. This class has a property MimeTypes of type MimeTypeCollection
public class MimeTypesSectionHandler : ConfigurationSection
{
[ConfigurationProperty("mimeTypes", IsDefaultCollection = true)]
public MimeTypesCollection MimeTypes
{
get { return this["mimeTypes"] as MimeTypesCollection; }
}
}

The MimeTypesCollection class inherits from ConfigurationElementCollection. Its stores a collection of objects of type MimeTypeConfigElement
[ConfigurationCollection(typeof(MimeTypeConfigElement))]
public class MimeTypesCollection : ConfigurationElementCollection
{
public new MimeTypeConfigElement this[string ext]
{
get
{
return BaseGet(ext) as MimeTypeConfigElement;
}
}

public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType.AddRemoveClearMap;
}
}

protected override object GetElementKey(ConfigurationElement element)
{
return ((MimeTypeConfigElement)element).Ext;
}

protected override ConfigurationElement CreateNewElement()
{
return new MimeTypeConfigElement();
}
}

The MimeTypeConfigElement inherits from ConfigurationElement. It has two properties - Ext and ContentType.
public class MimeTypeConfigElement : ConfigurationElement
{
[ConfigurationProperty("ext", IsRequired = true, IsKey = true)]
public String Ext
{
get { return (String)this["ext"]; }
set { this["ext"] = value; }
}

[ConfigurationProperty("contentType", IsRequired = true)]
public String ContentType
{
get { return (String)this["contentType"]; }
set { this["contentType"] = value; }
}
}

That's all the code we need to write. Just add a section within the configSections element in the web.cofig file.



And add your custom section



You can add to this list with all kinds of file extensions without installing a single application on your system.

Now our GetContentType method changes to -
private static MimeTypesCollection mimeTypesSettings = 
((MimeTypesSectionHandler)ConfigurationManager
.GetSection("mimeTypes")).MimeTypes;

public static MimeTypesCollection MimeTypesSettings
{
get { return mimeTypesSettings; }
}

...

public string GetContentType(string fname)
{
// set a default mimetype if not found.
string contentType = "application/octet-stream";

try
{
contentType = MimeTypesSettings[Path.GetExtension(fname)].ContentType;
}
catch { }

return contentType;
}


kick it on DotNetKicks.com

1 comment:

Anonymous said...

Hi Rohit,
Is this browser specific? Because, when I am downloading a file through chrome or IE, I am able to download the file with the extension. But when i try to do that with firefox, I am downloading a file with no extension. Its asking me to open with some applications. When I browsed for this problem , I found that Firefox was unable to handle the mime types.
So, I don't no how to resolve this .
Thank you.

Post a Comment

I am a programmer based in Seattle, WA. This is a space where I put notes from my programming experience, reading and training. To browse the list of all articles on this site please go here. You can contact me at rohit@rohit.cc.