Dynamically Determine MIME Types in C#

Suppose you need to determine the MIME type for a given file extension in your code. Since Windows already knows many MIME types and since these MIME type are constantly updating, it seems a good idea to use Windows’ data instead of including a table of MIME types into your code by yourself.

Luckily, the needed data is very easily accessible. In the Windows Registry, there is a registry key for each known file extension right underneath HKEY_CLASSES_ROOT. The registry key might contains a value named “Content Type”. Now guess what – that value is the MIME type! Hurray!

For your convenience, here’s the full code:

using System;
using System.IO;
using Microsoft.Win32;

namespace MunirHusseini
{
    public static class ContentTypeHelper
    {
        /// <summary>
        /// Gets the MIME type corresponding to the extension of the specified file name.
        /// </summary>
        /// <param name="fileName">The file name to determine the MIME type for.</param>
        /// <returns>The MIME type corresponding to the extension of the specified file name, if found; otherwise, null.</returns>
        public static string GetContentType(string fileName)
        {
            var extension = Path.GetExtension(fileName);

            if (String.IsNullOrWhiteSpace(extension))
            {
                return null;
            }

            var registryKey = Registry.ClassesRoot.OpenSubKey(extension);

            if (registryKey == null)
            {
                return null;
            }

            var value = registryKey.GetValue("Content Type") as string;
            
            return String.IsNullOrWhiteSpace(value) ? null : value;
        }
    }
}
Advertisements

5 thoughts on “Dynamically Determine MIME Types in C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s