Question

I'm trying to get service executable path from services.msc

I wrote the next code:

  var service = ServiceController.GetServices().Where(p => p.ServiceName.Equals("Service name", StringComparison.InvariantCultureIgnoreCase));
if (service.Any())
//get service data

I couldn`t find where (if at all) the service executable path is located?

In services.msc I can see the path so I'm assuming it also possible to get it through code. Example of service info in services.msc (see that executable path exists there)

Any Ideas?

Was it helpful?

Solution

You can get it from the registry like so:

private static string GetServiceInstallPath(string serviceName)
{
    RegistryKey regkey;
    regkey = Registry.LocalMachine.OpenSubKey(string.Format(@"SYSTEM\CurrentControlSet\services\{0}", serviceName));

    if (regkey.GetValue("ImagePath") == null)
        return "Not Found";
    else
        return regkey.GetValue("ImagePath").ToString();
}

OTHER TIPS

Just a bit simplified version of @ChirClayton's code:

public string GetServiceInstallPath(string serviceName) => (string) Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\services\{serviceName}").GetValue("ImagePath");

It doesn't trim possible arguments of service. If they are not required, you can use following:

public string GetServiceInstallPath(string serviceName) 
{
    var imagePath = (string) Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\services\{serviceName}").GetValue("ImagePath");
    if (string.IsNullOrEmpty(imagePath))
        return imagePath;
    if (imagePath[0] == '"')
        return imagePath.Substring(1, imagePath.IndexOf('"', 1) - 1);
    var indexOfParameters = imagePath.IndexOf(' ');
    if (indexOfParameters >= 0)
        return imagePath.Remove(indexOfParameters);
    return imagePath;
}

You can use WMI to get full information about your service (local or remote service)

Check the code of ( Services+ on CodePlex ) about how to use WMI

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top