I have an IIS7 web server that runs loads of sites each with multiple bindings. Each site uses host headers AND their own IP.
Using C# I need to change the IP on all bindings to 0.0.0.0 so they listen on all the IPs.
My current code doesn’t add the new bindings but clears the old ones. Any ides what I’m doing wrong?
My Code:
using (ServerManager iisServerManager = new ServerManager())
{
foreach (Site site in iisServerManager.Sites)
{
List<Microsoft.Web.Administration.Binding> bindings = new List<Microsoft.Web.Administration.Binding>();
foreach (Microsoft.Web.Administration.Binding binding in site.Bindings)
{
String protocol = binding.Protocol;
String hostHeader = binding.Host;
String ipAddress = "0.0.0.0";
Int32 port = binding.EndPoint.Port;
String bind = ipAddress + ":" + port + ":" + hostHeader;
binding.BindingInformation = bind;
bindings.Add(binding);
}
//Clear existing site bindings
site.Bindings.Clear();
Int32 bindingCount = site.Bindings.Count();
foreach (Microsoft.Web.Administration.Binding binding in bindings)
{
site.Bindings.Add(binding);
bindingCount = site.Bindings.Count();
}
bindingCount = site.Bindings.Count();
iisServerManager.CommitChanges();
}
}
You don’t need to remove and then re-add the same bindings. You can just modify them in place and then commit your changes. Also, you want to use the ip address of ‘*’ instead of ‘0.0.0.0’ when you want to listen on all ip addresses.
This worked for me…