How to get app port from IIS Express in C#

487 Views Asked by At

I am trying to get The port which an app is running on, from IIS Express.

So far i tried those two approaches:

//first
var iisExpress = new DirectoryEntry("IIS://localhost/W3SVC/AppPools").Children;

//second
var mgr = new ServerManager().Sites;

But both give me only the DefaultAppPool with the Default Web App, while what i need is the apps i'm running localy from Visual Studio.

1

There are 1 best solutions below

3
Kermode On

This will output the names and ports of all your websites running on IIS.

var serverManager = new ServerManager();
    
foreach (Site site in serverManager.Sites)
{
   Console.WriteLine(site.Name);
   Console.WriteLine(site.Bindings[0].EndPoint.Port);
}

If you want to save the port of a specific site (ex: MyWebsite) on a variable you can do the following:

var serverManager = new ServerManager();
var mySite = serverManager.Sites.FirstOrDefault(s => s.Name.Contains("MyWebsite"));
int myPort = mySite?.Bindings[0].EndPoint.Port ?? 0;