Bob Jones
Bob Jones

Reputation: 475

Code to create IIS Website

I need to programatically create an IIS website. Can anybody show me the code to do this?

Upvotes: 3

Views: 3411

Answers (2)

Carlos Aguilar Mares
Carlos Aguilar Mares

Reputation: 13581

Please don't use WMI (DirectoryEntry) if at all possible when targeting IIS 7 or above. There is an API called ServerManager in the Microsoft.Web.Administration.dll (windows\system32\inetsrv) that makes this really easy:

ServerManager serverManager = new ServerManager();
serverManager.Sites.Add("Mysite", "c:\temp\", 8080);

Upvotes: 4

John
John

Reputation: 112

This will work for IIS 6.0 and later, it's written in VB.Net (which, this is small enough to easily to convert to C# if needed). I also didn't write this, I found it here (I did compile it though to make sure it would build): http://www.gafvert.info/notes/VBNET-Create-Website-IIS6.htm

VB Version

Imports System.DirectoryServices
Imports System

Public Class IISAdmin
    Public Shared Function CreateWebsite(webserver As String, serverComment As String, serverBindings As String, homeDirectory As String) As Integer
        Dim w3svc As DirectoryEntry
        w3svc = New DirectoryEntry("IIS://localhost/w3svc")

        'Create a website object array
        Dim newsite() As Object
        newsite = New Object(){serverComment, new Object(){serverBindings}, homeDirectory}

        'invoke IIsWebService.CreateNewSite
        Dim websiteId As Object
        websiteId = w3svc.Invoke("CreateNewSite", newsite)

        Return websiteId

    End Function

    Public Shared Sub Main(args As String())
        Dim a As Integer
        a = CreateWebsite("localhost", "Testing.com", ":80:Testing.com", "C:\\inetpub\\wwwroot")
        Console.WriteLine("Created website with ID: " & a)
    End Sub

End Class

C# Version

public static int CreateWebsite(string webserver, string serverComment, string serverBindings, string homeDirectory)
{
   DirectoryEntry w3svc = new DirectoryEntry("IIS://localhost/w3svc");

   //Create a website object array
   object[] newsite = new object[]{serverComment, new object[]{serverBindings}, homeDirectory};

   //invoke IIsWebService.CreateNewSite
   object websiteId = (object)w3svc.Invoke("CreateNewSite", newsite);

   return (int)websiteId;
}

Upvotes: 2

Related Questions