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

Freelance full-stack .NET and JS developer and architect. Located near Cologne, Germany.

5 thoughts on “Dynamically Determine MIME Types in C#

Leave a Reply

Your email address will not be published. Required fields are marked *