【问题标题】:Get service path from services.msc c#从 services.msc c# 获取服务路径
【发布时间】:2013-04-18 08:27:44
【问题描述】:

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

我写了下一段代码:

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

我找不到服务可执行路径的位置(如果有的话)?

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

有什么想法吗?

【问题讨论】:

标签: c# service servicecontroller


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2011-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-25
        • 2018-07-24
        • 2018-06-29
        • 1970-01-01
        • 2011-09-20
        相关资源
        最近更新 更多