0

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.

Machshevet
  • 21
  • 1

1 Answers1

0

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;
Kermode
  • 139
  • 11
  • Thank you for your answer. but as i mentioned, i already tried it. i'm only getting the "Default Web Site" and not the app i'm running from Visual Studio. – Machshevet Dec 19 '22 at 13:33
  • In my case the the first block of code outputs 3 sites even though I have more, however DefaultAppPool doesn't show up for me. I did notice that the 3 that have ports also have 1 or more Applications in the Application Pools tab and DefaultAppPool has 0 Applications. Can you check if the website you're trying to get the port from has any Application in the Application Pools tab and that it status is started ? – Kermode Dec 19 '22 at 13:46
  • I'm not sure what is the 'Application Pools tab' you are referring to. On debugging, when i look into `serverManager` properties, there is only one pool - `DefaultAppPool`, which contains one site - `Default Web Site`. – Machshevet Dec 20 '22 at 09:41