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?

4

3 回答 3

10

您可以像这样从注册表中获取它:

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();
}
于 2013-04-18T08:36:00.723 回答
0

只是@ChirClayton 代码的简化版本:

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

它不会修剪可能的服务论点。如果不需要它们,您可以使用以下内容:

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;
}
于 2017-06-06T10:18:45.787 回答
-1

您可以使用 WMI 获取有关您的服务(本地或远程服务)的完整信息

查看 ( Services+ on CodePlex ) 关于如何使用 WMI的代码

于 2014-10-17T13:28:00.243 回答