Create a Web Site in IIS Using C#

Ever wondered how to interface with IIS using .NET? If all your apps/clients are running IIS 6.0, it is drop dead easy, just enable the XML metabase and parse it to your heart's content. However, if you need to support older clients, you will probably end up using DirectoryServices. However, since DirectoryServices is fairly generic, you might have difficulty figuring out what exactly you need to do. In case you get stuck, here is a little reference block of code that will create a new web site with the supplied name and root directory:

public class SetupUtility

{

public SetupUtility()

{

}

public int CreateWebSite(string webSiteName, string pathToRoot)

{

return CreateWebSite(webSiteName, pathToRoot, false);

}

public int CreateWebSite(string webSiteName, string pathToRoot, bool createDir)

{

DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");

// Find unused ID value for new web site

int siteID = 1;

foreach(DirectoryEntry e in root.Children)

{

if(e.SchemaClassName == "IIsWebServer")

{

int ID = Convert.ToInt32(e.Name);

if(ID >= siteID)

{

siteID = ID+1;

}

}

}

// Create web site

DirectoryEntry site = (DirectoryEntry)root.Invoke("Create", "IIsWebServer", siteID);

site.Invoke("Put", "ServerComment", webSiteName);

site.Invoke("Put", "KeyType", "IIsWebServer");

site.Invoke("Put", "ServerBindings", ":80:");

site.Invoke("Put", "ServerState", 2);

site.Invoke("Put", "FrontPageWeb", 1);

site.Invoke("Put", "DefaultDoc", "Default.aspx");

site.Invoke("Put", "SecureBindings", ":443:");

site.Invoke("Put", "ServerAutoStart", 1);

site.Invoke("Put", "ServerSize", 1);

site.Invoke("SetInfo");

// Create application virtual directory

DirectoryEntry siteVDir = site.Children.Add("Root", "IISWebVirtualDir");

siteVDir.Properties["AppIsolated"][0] = 2;

siteVDir.Properties["Path"][0] = pathToRoot;

siteVDir.Properties["AccessFlags"][0] = 513;

siteVDir.Properties["FrontPageWeb"][0] = 1;

siteVDir.Properties["AppRoot"][0] = "LM/W3SVC/"+siteID+"/Root";

siteVDir.Properties["AppFriendlyName"][0] = "Root";

siteVDir.CommitChanges();

site.CommitChanges();

return siteID;

}

}

44 Comments

  • Great sample!

    I used it as the basis for a program I wrote recently, and I was getting an error message saying application unavailable whenever I tried to connect to the web site.



    As soon as I removed this line;

    siteVDir.Properties["AppRoot"][0] = "LM/W3SVC/"+siteID+"/Root"; the site was created correctly and I no longer got that error. All of the web sites being created by my program are asp.net sites so I am uncertain whether this occurs in all web sites or only asp.net sites.



    I checked the AppRoot property for several sites created manually in IIS and in each case the AppRoot property either didn't exist or was set to "".

  • Jesse you are a legend, I have been trying to figure this one out for ages. Thanks. Mike

  • Just in case anyone has any problems getting asp scripts after using the above code.



    Simply replace this line:

    siteVDir.Properties["AppRoot"][0] = "LM/W3SVC/"+siteID+"/Root";



    with this line:

    siteVDir.Properties["AppRoot"][0] = "/LM/W3SVC/"+siteID+"/Root";



    that one "/" makes all the difference. :)



    -Matt Brooks

  • I will add explanation and a link for the VB.NET code to be downloaded in a while.

  • thanks,but how about using in IIS5.0?

    soon i'll try.

  • This works perfectly fine in IIS 5.0.

  • Something to be aware of in IIS 6.0 is that the siteIDs are no longer sequential, they are random, so just adding 1 to the siteID does not necessarily mean you will get a unique siteID. A better approach would be generating a random number (as the IIS Manager appears to), checking if it exists, and if not using it, if so repeat.

  • Compiler Error Message: CS0234: The type or namespace name 'DirectoryServices' does not exist in the class or namespace 'System' (are you missing an assembly reference?)



    what's the question?

  • You need to add DirectoryServices.dll as a reference

  • I'm getting Access denied on when running the code. Are there special permissions I need to set?



    I copied the code verbatim, and called it with

    SetupUtility su = new SetupUtility ();



    su.CreateWebSite("test", "c:\inetpub\www\test", true);



    Exception details System.Runtime.InteropServices.COMException: Access is denied



    Source Error:



    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

  • Thanks for this.. Helped me a lot.



    If you want the website to be attached to the DefaultApplicationPool you need to do something like.



    DirectoryEntry siteVDir = site.Children.Add("Root", "IISWebVirtualDir");

    siteVDir.Properties["Path"][0] = pathToRoot;

    siteVDir.Properties["AccessScript"][0] = true;

    siteVDir.CommitChanges();

    siteVDir.Properties["AppFriendlyName"][0] = "Default Application";

    siteVDir.Invoke("AppCreate3", new object[] {2, "DefaultAppPool", true});

    siteVDir.CommitChanges();



    Not sure why it needs the double CommitChanges but its what I had to do to get it working for the ROOT

    virtual directory. Works without the double commit for others. Strange!

  • Same problem as will



    site.Invoke("SetInfo");



    causes an access denied.



    running IIS6 pls help

  • Oh I have forgotten one important thing concerning method 1. above. You need to have these two lines in web.config:

    <identity impersonate="true" />

    <authentication mode="Windows" />

  • Gracias :)

    you rock

  • Just curious. Is there any hard limits on how many IIS websites that can reside on a single IIS server?



    I have never broken 20 sites, but a new software piece I am developing could create up to 1000 sites.



    I couldn't imagine opening a enterprise manager with that many databases. wonder how iis will manage it.

  • How would you add more than one server binding. As i have to bind www.name.com and name.com to the site.

  • Has anyone come across a way to start/stop a specific web site in IIS through C#?



    ...And if so how?

  • _root = new DirectoryEntry("IIS://"+_serverName+"/W3SVC/1");

    _root.Password = _password;

    _root.Invoke("stop"); // and start

  • HI, i m trying to add host headers using above mentioned code as my bases, but so far i have not been able to figure which property respresent host headers, any clue?

  • Hi ,



    I am try to create a virtual folder with remote

    physical path using C# .It is crating but vitual

    folder has red mark and error. Pls give me replay .



    mail id is grnr02@yahoo.com

  • I'm in the process of setting up a hosted web server and I need to know how to set up a subdomain programmatically "subdomain.domain.com" in asp.net/vb.net

  • Hi, thank for your code.

    Is there a way to set the IP Address for the web site?

    I need to have several web site on the same 80 port so have I to set a unique IP address for each one or could I have different ways?

    Thank you

  • then HOW TO delete a website? and where could i find the Invoke's "methodName"? I searched msdn,and cann't find the "methodName"(such as "Create","Put" etc.)?

    my email:czj@6688.com. expecting your help!

  • Does anyone know how to change things like Anonymous Access and default documents?



  • IIS limits are around 1000, SQL is also the same but limit on tables per-db is 256.

  • download IIS 6 resource kit. It contains metabase explorer which will provide you with valuable information on the structure....



    Also a good idea to interate through the properties collection.

  • I followed your code and I can create a virtual directory properly in IIS. However, it didn't set the virtual folder as an application. I still have to go into IIS and create one manually by hitting button 'create' in 'home directory' of that particular virtual directory that I just created. Please let me know how could I accomplish this? Thank you in advance.

  • Wow. Great Reference. One question. I have several websites on my iis. now I want to get one of those to make some changes om it. How do I get a specific site in IIS when I don't know its ID?

  • I have tried to add SSL with client authentication using this approach to a virtual directory. As soon as the changes are commited, they are visible from the IIS configuration console, but I need to manually click the APPLY button to activate the changes so that a user gets prompted to select a certificate to access the virtual directory. How can I do this "apply" action programmatically? Thanks in advance.

  • then HOW TO get state a website?

  • How to creat an IP Base website ?

  • i just get confused with PathToRootmso please

    tell me what is it"

    is it the same localpath????

  • what is Pathtoroot,and how i can get the id

    of site which ahas been added before??

  • How to creat an IP Base website ?

  • can anybody tell me on how to set the ASP.Net version for a website through c#. By default the version is 1.1 and i want to set it to 2.0 through c#. Is this possible?

  • Found more help in this single blog than anywhere else.

    I had to convert the code to VB though. Works like a charm.

    I need a bit of help with this line. Instead of creating a site i would like to retrieve the information through this code. I think it is neat and clean.
    DirectoryEntry site = (DirectoryEntry)root.Invoke("Create", "IIsWebServer", siteID)

  • just created the class according to my own needs i can set up almost everything except the creation of new application pools and including it to the site plus some ssl configurations... but thats just about it.. im researching more this one really help me... thanks jesse

  • Hi
    I need to stop/start a website. I'm using IIS 5.1.
    How can this be performed with AD?
    Thanks.

  • Pl tell me the steps to create a subdomain using C#.NET

  • Hi,
    I'm using oWebSite.Invoke("Start") to start a web site.

    It works fine from visual studio in debug mode, but when I complie the code and put it in another web site I get an exception on the Invok ...

    anyone encountered this ?
    thanks

    rami

  • Hi, I've tried running the above code sample, but it did not reflect as what i'm expecting.

    could it be the permission settings? Do i need to impersonate the administrator user?

  • Hi,

    Is there anyone who as a complete library with different functions or know where to find one?
    I only find a few different functions not a more complete list.

    Anyone? =)

    Thanks!

  • can anybody tell me on how to set the ASP.Net version for a website through c#. By default the version is 1.1 and i want to set it to 2.0 through c#. Is this possible?

  • Hello Everyone! I like watching BBC Football online.

Comments have been disabled for this content.