Search code examples
asp.netiismimemime-types

ASP.NET/IIS6: How to search the server's mime map?


i want to find the mime-type for a given file extension on an IIS ASP.NET web-server from the code-behind file.

i want to search the same list that the server itself uses when serving up a file. This means that any mime types a web-server administrator has added to the Mime Map will be included.

i could blindly use

HKEY_CLASSES_ROOT\MIME\Database\Content Type

but that isn't documented as being the same list IIS uses, nor is it documented where the Mime Map is stored.

i could blindly call FindMimeFromData, but that isn't documented as being the same list IIS uses, nor can i guarantee that the IIS Mime Map will also be returned from that call.


Solution

  • Here's one I made earlier:

    public static string GetMimeTypeFromExtension(string extension)
    {
        using (DirectoryEntry mimeMap = 
               new DirectoryEntry("IIS://Localhost/MimeMap"))
        {
            PropertyValueCollection propValues = mimeMap.Properties["MimeMap"];
    
            foreach (object value in propValues)
            {
                IISOle.IISMimeType mimeType = (IISOle.IISMimeType)value;
    
                if (extension == mimeType.Extension)
                {
                    return mimeType.MimeType;
                }
            }
    
            return null;
    
        }
    }
    

    Add a reference to System.DirectoryServices and a reference to Active DS IIS Namespace Provider under the COM tab. The extension needs to have the leading dot, i.e. .flv.