2

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.

Cœur
  • 32,421
  • 21
  • 173
  • 232
user1336827
  • 1,476
  • 1
  • 13
  • 27

2 Answers2

1

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..

  • Great this worked to check if it is installed, now i just need to check the state to see if its running. Thanks. – user1336827 Oct 04 '17 at 20:09
  • 1
    I used if (mo.GetPropertyValue("PathName").ToString().Trim('"').StartsWith(fileInfo.FullName)) to ignore the command line params – user1336827 Oct 04 '17 at 20:10
0

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

Cyber Progs
  • 2,964
  • 3
  • 23
  • 32