如何使用.net获取Windows服务的物理路径?

时间:2010-04-28 10:23:02

标签: .net windows-services administration servicecontroller

我必须在.Net Admin应用程序中获取Windows服务的绝对路径。我正在使用.Net的ServiceController,如下所示。

ServiceController serviceController = new  ServiceController(serviceName);

但我在这里看不到任何属性来获取服务的.exe的绝对路径。无论如何都要以编程方式进行此操作。

2 个答案:

答案 0 :(得分:16)

您可以使用WMI获取此内容,这需要对System.Management的程序集引用:

using System.Management;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(GetPathOfService("eventlog"));
        Console.ReadLine();
    }

    public static string GetPathOfService(string serviceName)
    {
        WqlObjectQuery wqlObjectQuery = new WqlObjectQuery(string.Format("SELECT * FROM Win32_Service WHERE Name = '{0}'", serviceName));
        ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(wqlObjectQuery);
        ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();

        foreach (ManagementObject managementObject in managementObjectCollection)
        {
            return managementObject.GetPropertyValue("PathName").ToString();
        }

        return null;
    }
}

答案 1 :(得分:6)

如果它不是自己的程序集,您可以在注册表中查看:

HKLM\System\CurrentControlSet\Services\[servicename]\ImagePath

或者,如果您的意思是找到自己的程序集路径:

Assembly.GetExecutingAssembly().CodeBase;