Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从services.msc获取服务路径#_C#_Service_Servicecontroller - Fatal编程技术网

C# 从services.msc获取服务路径#

C# 从services.msc获取服务路径#,c#,service,servicecontroller,C#,Service,Servicecontroller,我正在尝试从services.msc获取服务可执行路径 我编写了下一个代码: var service = ServiceController.GetServices().Where(p => p.ServiceName.Equals("Service name", StringComparison.InvariantCultureIgnoreCase)); if (service.Any()) //get service data 我找不到服务可执行文件路径的位置(如果有的话) 在s

我正在尝试从services.msc获取服务可执行路径

我编写了下一个代码:

  var service = ServiceController.GetServices().Where(p => p.ServiceName.Equals("Service name", StringComparison.InvariantCultureIgnoreCase));
if (service.Any())
//get service data
我找不到服务可执行文件路径的位置(如果有的话)

在services.msc中,我可以看到路径,因此我假设也可以通过代码获取路径。


有什么想法吗?

您可以从注册表中获得,如下所示:

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();
}

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


检查()的代码,了解如何使用WMI

只是@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;
}

不确定它是否有助于此情况,但查看WindowsAPICodePack ShellFile类,看看它是否有助于访问此信息和