Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code to add a host header to an IIS Website

I have a single site that has many names. I want to be able to programatically add a new host header record to IIS to allow it to recognize another name. Specifically, what is the code (preferably in C#) to add a new host header to a given site?

like image 623
Bob Jones Avatar asked Apr 23 '09 23:04

Bob Jones


1 Answers

static void Main(string[] args)
{
    AddHostHeader(1, "127.0.0.1", 8080, "fred");
    AddHostHeader(1, null, 8081, null);
}

static void AddHostHeader(int? websiteID, string ipAddress, int? port, string hostname)
{
    using (var directoryEntry = new DirectoryEntry("IIS://localhost/w3svc/" + websiteID.ToString()))
    {
        var bindings = directoryEntry.Properties["ServerBindings"];
        var header = string.Format("{0}:{1}:{2}", ipAddress, port, hostname);

        if (bindings.Contains(header))
            throw new InvalidOperationException("Host Header already exists!");

        bindings.Add(header);
        directoryEntry.CommitChanges();
    }
}
like image 175
andleer Avatar answered Sep 29 '22 21:09

andleer