How to check Windows Service Status in C#
By FoxLearn 7/18/2024 7:49:05 AM 4.27K
How to check Windows Service Status in C#
Sometimes you may need to check the status of windows service, Here's a basic example of how you can do this:
Create a new Windows Forms Application, then design a simple UI as shown below. You can also use console application to run the code below.
Right-clicking on your Reference, then add System.ServiceProcess to your project.
Adding a click event handler to the check button allows you to check the windows service status.
private void btnCheck_Click(object sender, EventArgs e) { var service = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == txtServiceName.Text); if (service == null) lblStatus.Text = $"Service {txtServiceName.Text} not found!"; else lblStatus.Text = $"Service {txtServiceName.Text} is {service.Status}"; }
And don't forget to add the System.ServiceProcess
namespace to your form.
using System.ServiceProcess;
In this example, there is a Windows Forms application with a text box for entering the service name and a button to check its status. When the button is clicked, it tries to create a ServiceController
object with the specified service name. If the service exists, it retrieves its status and displays it in a Label
control. If the service doesn't exist or there is any error, it displays an error message.