IIS Home @ it-notebook.org

C# - Create a new website on IIS 6.0 by code

(Kristofer Gafvert, March 10, 2005)

Web hosting companies needs to frequently create and delete websites. Some web hosters even provide their customers with forms to create websites themselves. Others have so called control panels so their customers can control and administrate their own website. For this purpose, it is important to be able to create websites by code.

The following example creates a new website by using C# and ADSI. The method IIsWebService.CreateNewSite is only available in IIS 6.0 and later, and using this method is the prefered way to create new websites by code in IIS 6.0. This example does not specify the identification number, but if you want to do so, you can (see the reference for the method at the bottom of this page). After the website has been created, it will be stopped. The website can be started either manually, or by code (invoke the Start method).

1    using System.DirectoryServices;
2    using System;
3    
4    public class IISAdmin
5    {
6       public static int CreateWebsite(string webserver, string serverComment, string serverBindings, string homeDirectory)
7       {
8          DirectoryEntry w3svc = new DirectoryEntry("IIS://localhost/w3svc");
9          
10         //Create a website object array
11         object[] newsite = new object[]{serverComment, new object[]{serverBindings}, homeDirectory};
12         
13         //invoke IIsWebService.CreateNewSite
14         object websiteId = (object)w3svc.Invoke("CreateNewSite", newsite);
15         
16         return (int)websiteId;
17      
18      }
19   
20      public static void Main(string[] args)
21      {
22         int a = CreateWebsite("localhost", "Testing.com", ":80:Testing.com", "C:\\inetpub\\wwwroot");
23         Console.WriteLine("Created website with ID: " + a);
24      }
25      
26   }

Resources

Download code (CreateWebsiteIIS6.zip)
MSDN: IIsWebService.CreateNewSite