Skip to content

Instantly share code, notes, and snippets.

@vnisor
Forked from CharlTruter/gist:2110398
Created April 19, 2017 20:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vnisor/42ebcc196ab2d8675df46adfc191242c to your computer and use it in GitHub Desktop.
Save vnisor/42ebcc196ab2d8675df46adfc191242c to your computer and use it in GitHub Desktop.
How to change bindings on a site in IIS using C#
void ChangeSiteBinding(string siteName, string oldBindingValue, string newBindingValue, string protocol)
{
using (ServerManager manager = new ServerManager())
{
// Find the site by name from IIS
Microsoft.Web.Administration.Site site = manager.Sites.Where(q => q.Name == siteName).FirstOrDefault();
if (site == null)
{
throw new Exception("The specified site name does not exist in IIS!");
}
else
{
bool found = false;
// Loop through all the site's bindings
foreach (var binding in site.Bindings)
{
// If the binding protocol matches the passed protocol, continue
if (binding.Protocol.Equals(protocol))
{
// If the current binding value matches the old binding value passed, continue
if (binding.BindingInformation.Equals(oldBindingValue))
{
// Set this to indicate the binding was found
found = true;
// Set the binding value to the new passed value
binding.BindingInformation = newBindingValue;
break;
}
}
}
if (found)
{
// If the binding was found and changed, commit the changes.
manager.CommitChanges();
}
else
{
// If the binding was not found, throw an exception indicating as much.
throw new Exception("The specified old binding does not exist on this site!");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment