Resolving Mime Type/File Extension Mapping From IIS March, 2010
We ran into a situation where we needed to resolve a mime type for a file extension in a RESTful service running under IIS6. We didn't want to build a mapping ourselves somewhere but wanted to use a mapping that already existed. Here is a class that will do the mapping, using IIS as the source. You will need to add a reference to System.DirectoryServices and a reference to the "Active DS IIS Namespace Provider" COM component.
public static class MimeTypes { private static Dictionary<string, string> _mimeTypes; public static string ResolveMimeTypeFromExtension(string extension) { LoadMimeTypeMapping(); if (!extension.StartsWith(".")) extension = "." + extension; return _mimeTypes.ContainsKey(extension) ? _mimeTypes[extension] : null; } public static string ResolveExtensionFromMimeType(string mimeType) { LoadMimeTypeMapping(); return _mimeTypes.ContainsValue(mimeType) ? _mimeTypes.First(mapping => mapping.Value == mimeType).Key : null; } private static void LoadMimeTypeMapping() { if (_mimeTypes != null) return; _mimeTypes = new Dictionary<string, string>(); DirectoryEntry path = new DirectoryEntry("IIS://localhost/MimeMap"); PropertyValueCollection mimeMap = path.Properties["MimeMap"]; foreach (var mapping in mimeMap.OfTypeIISMimeType>()) _mimeTypes.Add(mapping.Extension, mapping.MimeType); } }