Finding the actual executable and path associated with a Windows service using C #

I am working on an installation program for one of my company products. The product can be installed several times, and each installation is a separate Windows service. When users update or reinstall the program, I would like to look at the running services, find the services related to the product, and then find the executable and its path for this service. Then use this information to find which of the services the user wants to update / replace / install / etc. In the code example below, I see the service name, description, etc., but I don’t see the actual file or path name. Can someone please tell me what I am missing? Thank you in advance!

The code I have is as follows:

ServiceController[] scServices; scServices = ServiceController.GetServices(); foreach (ServiceController scTemp in scServices) { if (scTemp.ServiceName == "ExampleServiceName") { Console.WriteLine(); Console.WriteLine(" Service : {0}", scTemp.ServiceName); Console.WriteLine(" Display name: {0}", scTemp.DisplayName); ManagementObject wmiService; wmiService = new ManagementObject("Win32_Service.Name='" + scTemp.ServiceName + "'"); wmiService.Get(); Console.WriteLine(" Start name: {0}", wmiService["StartName"]); Console.WriteLine(" Description: {0}", wmiService["Description"]); } } 
+6
source share
1 answer

Maybe I'm wrong, but the ServiceController class does not provide this information directly.

So, as Gene suggested, you have to use the registry or WMI.

An example of using the registry is at http://www.codeproject.com/Articles/26533/A-ServiceController-Class-that-Contains-the-Path-t

If you decide to use WMI (which I would prefer),

 ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Service"); ManagementObjectCollection collection = searcher.Get(); foreach (ManagementObject obj in collection) { string name = obj["Name"] as string; string pathName = obj["PathName"] as string; ... } 

You can decide to wrap the properties you need in the class.

+9
source

Source: https://habr.com/ru/post/911439/


All Articles