This code snippet shows how to programmatically create a new website in IIS via C# and ADSI

// ------------------------
// This requires the following using statement
using System.DirectoryServices;
// ------------------------

// Connect to he ADSI Provider
DirectoryEntry w3svc = new DirectoryEntry("IIS://localhost/w3svc");

// For a new website we need 3 things:
// Server Comment - The name of the site as displayed by the IIS Manager
// Server Bindings - The hostheader for the site in the form of IP:PORT:DOMAIN
// Web root - Where the home directory for the new site resides on the local computer

// We begin by creating a new object which will store our desired settings
object[] newSiteConfig = new object[] { "My New Website", new object[] { "127.0.0.1:80:domain.tld" }, @"C:\webroot" };

// Then we invoke the CreateNewSite method on the w3svc object giving it our newSiteConfig as a base
object websiteId = (object)w3svc.Invoke("CreateNewSite", newSiteConfig);

// And if we want we can get the IIS Identifier for the new created Web Site by casting it into an integer
int WebSiteId = (int)websiteId;
Tagged with: