ASP.NET Check If A Program Running or Not

visual-studio-asp-net

Sometimes we want to check whether a program is running silently at the background and most of us want to know if it is not doing so, get an email or an SMS.

The web applications we publish should be constantly monitored against downtimes.

Recently I found a decent way to see this by checking the port the application runs by a service. Here you can find a tutorial about creating and running a Windows service: https://anilbektas.com/2019/08/26/creating-windows-services-the-definitive-guide/

Check Whether A Port Is Getting Listened

To find out a port whether is listened by an application or not, I found a legitimate solution in ASP.NET after countless of hours and trial-errors.

The code is as follows:

public bool Is5001Available()
{
int port = 5001;
var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();

foreach (TcpConnectionInformation tcpi in tcpConnInfoArray)
{
if (tcpi.LocalEndPoint.Port == port)
{
return false;
}
}
return true;
}

What does this code mean?

This code means that if a port is available, in this case, the method is returning true, your application is not running correctly. I mean the application supposedly listen that port. Again bear in mind, if this method runs false then your application is running and listening this port.

With love,