How can I get the port by websites name via C# from IIS?
Asked Answered
O

1

8

In IIS-Manager, the default web site is bound on port 80. How can I get the port by website-name, using c#? I tried the following code:

var lWebsite = "Default Web Site";
var lServerManager = new ServerManager();
var lPort = lServerManager.Sites[lWebsite].Bindings.GetAttributeValue("Port");

lPort results in null with an invalid index exception. But the assignment var lPort = lServerManager.Sites[lWebsite] works.

Olein answered 7/4, 2014 at 12:8 Comment(3)
Please check the below link.#11617106Shellyshelman
One more link in msdn forum. social.msdn.microsoft.com/Forums/vstudio/en-US/…Shellyshelman
@Jayesh Goyani: bindingNode.Attribute("Port").Value does also not work.Olein
P
14

When you access Sites[lWebsite].Bindings, you're accessing a collection of bindings. When you then try to call GetAttributeValue("Port"), it fails because that makes no sense - the collection itself doesn't have a port number associated with it, it's just a collection.

If you want to get access to the port number used by each binding, you need to loop through those bindings and ask each one for its associated port number:

var site = lServerManager.Sites[lWebsite];
foreach (var binding in site.Bindings)
{
    int port = binding.EndPoint.Port;
    // Now you have this binding's port, and can do whatever you want with it.
}

It's worth highlighting the fact that websites can be bound to multiple ports. You talk about getting "the" port, but that's not necessarily the case - for example, a website that's served over both HTTP and HTTPS will have two bindings, usually on ports 80 and 443. That's why you're having to deal with a collection of bindings, even though in your case that collection may only contain one binding it's still a collection.

For further details, have a look at the MSDN documentation for the Binding class. Note that some of what you're likely to be interested in will involve accessing the binding's EndPoint property, as in the sample above.

Peonage answered 9/4, 2014 at 12:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.