views:

70

answers:

2

I have to get the absolute path of a windows service in a .Net Admin application. I am using ServiceController of .Net as shown below.

ServiceController serviceController = new  ServiceController(serviceName);

But I don't see any property here to get the absolute path of the .exe of the service. Is there anyway to get this programmatically.

+1  A: 

If it's not it's own assembly you can look in the registry at:

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

Or if you mean find your own assembly's path:

Assembly.GetExecutingAssembly().CodeBase;
ho1
+1  A: 

You can get this using WMI:

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;
    }
}
Daniel Renshaw