Search code examples
c#iismime-typesvirtual-directory

Add Mime Type to a virtual directory


I want to add a MIME type to the newly created virtual directory, which is under 'Default Web Site'.

using (ServerManager manager = new ServerManager())
{
ServerManager manager = new ServerManager();
var vdir = manager.Sites["Default Web Site"].Applications["/"].VirtualDirectories["VDir"];
}

I haven't been able to find appropriate examples/documentation where I can do it for a virtual directory (and not for a website), without using DirectoryServices. Any suggestions?


Solution

  • Have you tried it like this (slight modification of the example on IIS.NET):

    using System;
    using System.Text;
    using Microsoft.Web.Administration;
    
    internal static class Sample
    {
       private static void Main()
       {
          using (ServerManager serverManager = new ServerManager())
          {
             Configuration vDirConfig = serverManager.GetWebConfiguration("Default Web Site", "/VDir");
             ConfigurationSection staticContentSection = vDirConfig.GetSection("system.webServer/staticContent");
             ConfigurationElementCollection staticContentCollection = staticContentSection.GetCollection();
    
             ConfigurationElement mimeMapElement = staticContentCollection.CreateElement("mimeMap");
             mimeMapElement["fileExtension"] = @"bla";
             mimeMapElement["mimeType"] = @"application/blabla";
             staticContentCollection.Add(mimeMapElement);
    
             ConfigurationElement mimeMapElement1 = staticContentCollection.CreateElement("mimeMap");
             mimeMapElement1["fileExtension"] = @"tab";
             mimeMapElement1["mimeType"] = @"text/plain";
             staticContentCollection.Add(mimeMapElement1);
    
             serverManager.CommitChanges();
          }
       }
    }