finding the actual executable and path associated to a windows service using c#

假如想象 提交于 2019-12-01 14:57:37

问题


I am working on an installation program for one of my company's product. The product can be installed multiple times and each installation represents a separate windows service. When users upgrade or reinstall the program, I would like to look up the services running, find the services that belong to the product, and then find the executable file and its path for that service. Then use that information to find which one of the services the user wishes to upgrade/replace/install/etc. In my code example below, I see the service name, description, etc, but don't see the actual filename or path. Could someone please tell me what I'm 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"]);
            }
        }

回答1:


I might be wrong but the ServiceController class doesn't provide that information directly.

So as suggested by Gene - you will have to use the registry or WMI.

For an example of how to use the registry, refer to 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 a class.




回答2:


the interface has changed since @sidprasher answered, try:

var collection = searcher.Get().Cast<ManagementBaseObject>()
        .Where(mbo => mbo.GetPropertyValue("StartMode")!=null)
        .Select(mbo => Tuple.Create((string)mbo.GetPropertyValue("Name"), (string)mbo.GetPropertyValue("PathName")));


来源:https://stackoverflow.com/questions/9828588/finding-the-actual-executable-and-path-associated-to-a-windows-service-using-c-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!