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; } } }
You just solved my problem with this. Thank you
This is helpful ..
This only works if the application is installed on the machine, which may not be the case on a web server.
from .net version 4.5 it should be better to use this:
https://msdn.microsoft.com/en-us/library/system.web.mimemapping.getmimemapping.aspx
Very good point. Thank you.