4

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?

Ofir
  • 5,049
  • 5
  • 36
  • 61
  • not sure if it will help this case, but it may help to look at the WindowsAPICodePack ShellFile class and see if it can help access this information – Thewads Apr 18 '13 at 08:32
  • 1
    [**how to get phyiscal path of windows service using .net?**](http://stackoverflow.com/questions/2728578/how-to-get-phyiscal-path-of-windows-service-using-net) and [**A ServiceController Class that Contains the Path to the Executable**](http://www.codeproject.com/Articles/26533/A-ServiceController-Class-that-Contains-the-Path-t) – Damith Apr 18 '13 at 08:36

3 Answers3

10

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();
}
razethestray
  • 666
  • 1
  • 9
  • 20
0

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

Sameh
  • 934
  • 1
  • 14
  • 40
0

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;
}
Alex Zhukovskiy
  • 9,565
  • 11
  • 75
  • 151