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?
+2
A:
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();
}
}
Andrew Robinson
2009-04-24 16:58:21
A:
I tried this code in an ASP.NET page and I am getting "System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) at System.DirectoryServices.Interop.UnsafeNativeMethods.IAds.SetInfo()".
Any help is much appreciated.
Thanks in advance,
Kiran Banda
Kiran Banda
2009-10-26 11:42:20
Your IIS anonymous user needs to be an administrator to be able to do this.
Kev
2010-02-01 17:55:52