Creating an IIS Site through managed code

Another task I had in the past along with creating the DNS entries via managed code, was creating a new site in IIS. I had to nip various code from various places, but when I got done, it all worked nicely together. You will notice by the try catch block, that again, I was executing this chunk of code from a web based application. Needless to say, chances are you won’t have the permissions to do this unless you do. This code works on IIS 6.0 with Windows 2003 Server Std Edition . I’d imagine it’s more IIS specific than OS specific, but this is the only version of Windows I’ve tested it with.

public static string CreateWebSite(string NewSiteIP, string webSiteName, string pathToRoot, string DomainName)
    int siteID = 1;
    string sSiteID = “”;

        CreatePhysicalDirectory(pathToRoot, webSiteName);

        ManagementScope _scope = new ManagementScope(@”\\WINDOWS\root\MicrosoftIISV2″, null);

        ManagementObject oW3SVC = new ManagementObject(_scope, new ManagementPath(@”IIsWebService=’W3SVC’”), null);
        DirectoryEntry root = new DirectoryEntry(”IIS://WINDOWS/W3SVC”);

        #region get a good site id
        foreach (DirectoryEntry e in root.Children)
            if (e.SchemaClassName == “IIsWebServer”)
                int ID = Convert.ToInt32(e.Name);
                if (ID >= siteID)
                    siteID = ID + 1;

        ManagementScope mScope = null;
        ManagementPath mPath = new ManagementPath();
        mPath.ClassName = “ServerBinding”;
        mPath.NamespacePath = “root\\MicrosoftIISv2″;
        mScope = new ManagementScope(mPath);
        mScope.Path.Server = “WINDOWS”;

        #region Create the new Site
        ManagementBaseObject[] serverBindings = new ManagementBaseObject[2];
        serverBindings[0] = CreateServerBinding(DomainName, NewSiteIP, “80″);
        serverBindings[1] = CreateServerBinding(”www.” + DomainName, NewSiteIP, “80″);

        ManagementBaseObject inputParameters = oW3SVC.GetMethodParameters(”CreateNewSite”);
        inputParameters["ServerComment"] = ConfigurationManager.AppSettings["SitePrefix"] + webSiteName;
        inputParameters["ServerBindings"] = serverBindings;
        inputParameters["PathOfRootVirtualDir"] = pathToRoot + webSiteName;
        inputParameters["ServerId"] = siteID;

        ManagementBaseObject outParameter = null;
        outParameter = oW3SVC.InvokeMethod(”CreateNewSite”, inputParameters, null);
        // return is like IIsWebServer=’W3SVC/2145288186′

        sSiteID = Convert.ToString(outParameter.Properties["ReturnValue"].Value).Replace(”IIsWebServer=’W3SVC/”,”").Replace(”‘”,”");

        ManagementObject site = new ManagementObject(_scope,
            new ManagementPath(Convert.ToString(outParameter.Properties["ReturnValue"].Value)),

        #region Remap ScriptMaps
        ManagementObjectSearcher searcher = new ManagementObjectSearcher(@”root\MicrosoftIISv2″,
            “SELECT * FROM IIsWebVirtualDirSetting WHERE Path = ‘” + pathToRoot.Replace(@”\”,@”\\”) + webSiteName + “‘”) ;

        foreach(ManagementObject queryObj in searcher.Get())
            if (queryObj.Properties["ScriptMaps"] != null)
                Object[] arrScriptMaps = (Object[])(queryObj["ScriptMaps"]);
                foreach (Object arrValue in arrScriptMaps)
                    foreach (PropertyData data in ((ManagementBaseObject)arrValue).Properties)
                            if (data.Name == “ScriptProcessor”)
                                data.Value = @”c:\windows\\framework\v2.0.50727\aspnet_isapi.dll”;
                queryObj.SetPropertyValue(”ScriptMaps”, arrScriptMaps);

        ManagementPath myPath = new ManagementPath();
        myPath.Path = @”IIsWebVirtualDirSetting.Name=’W3SVC/” + siteID.ToString() + “/root’”;
        ManagementObject oWebVDir = new ManagementObject(_scope, myPath, null);

        oWebVDir.Properties["AppFriendlyName"].Value = “mah new app”;
        oWebVDir.Properties["AccessRead"].Value = true;
        //oWebVDir.Properties["ServerAutoStart"].Value = true;
        oWebVDir.Properties["AuthFlags"].Value = 5; // Integrated Windows Auth.
        oWebVDir.Properties["AccessScript"].Value = true;
        oWebVDir.Properties["AuthAnonymous"].Value = true;
        oWebVDir.Properties["AppPoolId"].Value = “MyAppPoolName”;

        site.InvokeMethod(”Start”, null);
    catch (Exception ex)
        HttpContext.Current.Response.Write(ex.Message + “<BR>”);

    return sSiteID;

private static void CreatePhysicalDirectory(string pathToRoot, string webSiteName)
    if (Directory.Exists(pathToRoot + webSiteName))
        throw new Exception(”Error creating new website: Customer root directory already exists at ” + pathToRoot + webSiteName);
        Directory.CreateDirectory(pathToRoot + webSiteName);
        //StreamWriter indexFile = new StreamWriter(pathToRoot + webSiteName + @”\index.htm”, false, System.Text.Encoding.ASCII);
        //indexFile.Write(”<html><body><br><br><br><br><center><h2><font name=’Verdana’>Welcome to <font color=’green’> ” + webSiteName + “</font></font></h2></center></body></html>”);

/// <summary>
/// Adds a host header value to a specified website. WARNING: NO ERROR CHECKING IS PERFORMED IN THIS EXAMPLE.
/// </summary>
/// <param name=”hostHeader”>The host header. Must be in the form IP:Port:Hostname </param>
/// <param name=”websiteID”>The ID of the website the host header should be added to </param>
private static void AddHostHeader(string hostHeader, string websiteID)
    DirectoryEntry site = new DirectoryEntry(”IIS://localhost/w3svc/” + websiteID);
        //Get everything currently in the serverbindings propery.
        PropertyValueCollection serverBindings = site.Properties["ServerBindings"];

        //Add the new binding

        //Create an object array and copy the content to this array
        Object[] newList = new Object[serverBindings.Count];

        serverBindings.CopyTo(newList, 0);
        //Write to metabase

        site.Properties["ServerBindings"].Value = newList;

        //Commit the changes

    catch (Exception e)

public static ManagementObject CreateServerBinding(string HostName, string IP, string Port)
    ManagementScope _scope = new ManagementScope(@”\\WINDOWS\root\MicrosoftIISV2″);

    ManagementClass classBinding = new ManagementClass(_scope, new ManagementPath(”ServerBinding”), null);
    ManagementObject serverBinding = classBinding.CreateInstance();
    serverBinding.Properties["Hostname"].Value = HostName;
    serverBinding.Properties["IP"].Value = IP;
    serverBinding.Properties["Port"].Value = Port;
    return serverBinding;

Leave a Reply

Your email address will not be published. Required fields are marked *