While Mime Types are simple to add through the IIS 7.0 Configuration Manager, there are occasions where you’ll need to add them programmatically.  While there are several shell-driven options available ( powershell or the appcmd.exe utility ), IIS 7.0 includes a managed interface that is quite powerful in what it provides. 
 

The actual code interface lies in the Microsoft.Web.Administration.dll, and can be found in the IIS directory in your %WINDOW%\System32\inetsrv folder.  The entire interface revolves around the ServerManager class, which is the entry-point into the IIS configuration system.  With the ServerManager class, you can do everything from creating and managing sites, applications and virtual directories, to directly modify the IIS configuration files.

As an example, I created some sample code to add a .xap ( Silverlight ) mime-type to IIS for a silent install on a client machine:
 
ServerManager serverManager = new ServerManager();
string extension = ".xap";
string mimeType = "application/x-silverlight-app";

// Pulll the config for the default website
Configuration webConfig = serverManager.GetWebConfiguration("Default Web Site");

// mime maps live in Configuration/system.webServer/staticContent 
ConfigurationSection staticContentSection = webConfig.GetSection("system.webServer/staticContent");

// let's check if the current map exists
var existingMimeMap = from mimeMaps in staticContentSection.GetCollection()
                      where mimeMaps.Attributes["fileExtension"].Value.ToString().ToLower() == extension.ToLower()
                      select mimeMaps;

if (existingMimeMap.Count() == 0)
{
    // Configuration elements must be created by the collection that will consume it
    ConfigurationElement mimeMapElement = staticContentSection.GetCollection().CreateElement("mimeMap");
    
    // set the attributes for the map
    mimeMapElement.SetAttributeValue("fileExtension", extension);
    mimeMapElement.SetAttributeValue("mimeType", mimeType);

    staticContentSection.GetCollection().Add(mimeMapElement);

    // after commit, the mimetype will be active for the current site
    serverManager.CommitChanges();
}

And that’s all that’s required to open the configuration, add mime-type, and save the changes back to IIS.  Once CommitChanges is called, you can immediately see the results reflected in IIS ( in this case, you’ll be able to download Silverlight .xap files ).

The managed interface is quite powerful in it’s capabilities, and I’ll be covering more of it’s features in future posts.

- Colin