user1336827
user1336827

Reputation: 1826

Programmatically check if a windows service is running c#

I am writing an app to check to see if certain software is installed. One of my cases im looking for a service. I know the full path of the service. i.e. "c:\some folder\MyService.exe" I want to check to see if the service is installed and running. I have tried process.GetProcessbyName, but running into issues with 64 bit vs 32 bit processes. I've also tried ManagementObject but i keep getting invalid object path. Is it possible to get a service knowing only the path to the executable?

I know only the name and path of the executable. There may be more than one version of the executable as well, each with a different service name, which i do not have.

Upvotes: 2

Views: 7251

Answers (2)

Cyber Progs
Cyber Progs

Reputation: 3873

Here is how you can check if the service is installed or not , also get the status of the service

public static string CheckService(string ServiceName)
        {
            //check service
            var services = ServiceController.GetServices();
            string serviceStatu = string.Empty;
            bool isServiceExist = false;
            foreach (var s in services)
            {
                if (s.ServiceName == ServiceName)
                {
                    serviceStatu = "Service installed , current status: " + s.Status;
                    isServiceExist = true;
                }


            }

            if (!isServiceExist)
            {
                serviceStatu= "Service is not installed";
            }

            return serviceStatu;
        }

Console.WriteLine(CheckService("Service name"));

you need to add System.ServiceProcess to the project reference

Upvotes: 2

farzaaaan
farzaaaan

Reputation: 410

Try looking into the ServiceController / Management object for the executable path. Then based the executable path determine whether the service is running.

How to get executable path : [1] [2] [3]

Borrowed from an answer above

ManagementClass mc = new ManagementClass("Win32_Service");
foreach(ManagementObject mo in mc.GetInstances())
{
    if(mo.GetPropertyValue("PathName").ToString().Trim('"') == "<your executable path>")
    {
        return mo.GetPropertyValue("Name").ToString(); // or return true;
    }
}

I haven't tested this, and a comment suggested PathName may return command line arguments as well, so you may need to write another method to separate the path from the arguments (I'm assuming it'll just be a split on the string), and pass PathName to it in If statement..

Upvotes: 1

Related Questions