views:

139

answers:

2

If I right-click and choose Properties on a service (like, say, Plug and Play) in the Services dialog, I get several pieces of information, including "Path to executable". For Plug and Play (in Vista) this is:

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

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

(I can't use GetExecutingAssembly() because I'm not running the service from my project.)

+2  A: 

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

The basic process is:

Call OpenSCManager to get a handle to the services managed.

Call OpenService to get a handle to the service.

Call QueryServiceConfig to get the QUERY_SERVICE_CONFIG structure.

Reed Copsey
A: 

Another option, without the interop, would be a WMI lookup (or registry - bit hacky!).

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;
}
Dave Cluderay