Windows service location * not * in my project

If I right-click and from the Services menu, select Properties for a service (eg Plug and Play), I get a few pieces of information, including the path to the executable file. For Plug and Play (in Vista), these are:

C: \ Windows \ system32 \ svchost.exe -k DcomLaunch

Is there a way to get this same piece of information using .NET code if I know the service name (and / or display name)?

(I cannot use GetExecutingAssembly()

because I am not starting the service from my project.)

+1


a source to share


3 answers


Another option, without interaction, would be a WMI lookup (or registry - bit hacked!).

Here's a quick example based on this code :



private static string GetServiceImagePathWMI(string serviceDisplayName)
{
    string query = string.Format("SELECT PathName FROM Win32_Service WHERE DisplayName = '{0}'", serviceDisplayName);
    using (ManagementObjectSearcher search = new ManagementObjectSearcher(query))
    {
        foreach(ManagementObject service in search.Get())
        {
            return service["PathName"].ToString();
        }
    }
    return string.Empty;
}

      

+3


a source


This information is in the QUERY_SERVICE_CONFIG structure . You will need to use P / Invoke to get it.

Main process:

Call OpenSCManager to access managed services.



Call OpenService to get a handle to this service.

Call QueryServiceConfig to get the QUERY_SERVICE_CONFIG structure.

+1


a source


There is always a WMI class Win32_Service

, as described here in particular PathName

.

It works:

ManagementClass mc = new ManagementClass("Win32_Service");
foreach(ManagementObject mo in mc.GetInstances())
{
    if(mo.GetPropertyValue("Name").ToString() == "<Short name of your service>")
    {
        return mo.GetPropertyValue("PathName").ToString().Trim('"');
    }
}

      

If you have a link problem, add the System.Management link to your project.

+1


a source







All Articles