Search code examples
c#iiswebportservermanager

how check if port is currently used with IIS7 (webSite) in code behind?


I developed a program "installer" that will add and configure a new website on IIS. My problem is that I want to check if the port given by the user is already used by another site before installing.

My project is in C # WinForm style. Someone you have an idea?

string[] lPorts = System.IO.Ports.SerialPort.GetPortNames(); ?

Solution

  • Check this:

    BindingInformation Property: Gets or sets the binding information for the current binding.

    The value of this property is a colon-delimited string that includes the IP address, port, and host name of the binding. You can leave the host name blank. You can set the IP address to "*" to indicate that the binding works for all variables.

    For example, a binding that is set for all IP addresses on port 80 and has no specified host name returns ":80:" from this property. A binding that is set for IP address 192.168.1.150 on port 8080 returns "192.168.1.150:8080:". A binding that is set for all IP addresses on port 80 for a host named "microsoft.com" returns ":80:microsoft.com".

    The BindingInformation property values are maintained in the ApplicationHost.config file.

    Also, you can check this: Get IIS bindings at runtime

    foreach (Microsoft.Web.Administration.ConfigurationElement binding in mySite.GetCollection("bindings"))
            {
                string protocol = (string)binding["protocol"];
                string bindingInfo = (string)binding["bindingInformation"];
    
                if (protocol.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                {
                    string[] parts = bindingInfo.Split(':');
                    if (parts.Length == 3)
                    {
                        //Get the port in use HERE !!!
                        string port = parts[1];
                        yield return new KeyValuePair<string, string>(protocol, port);
                    }
                }
            }