Search code examples
c#windows-services

How to retrieve the path to executables from services.msc using c#?


How to get the below high lighted data from windows services using c#?

enter image description here

I have tried the below code to get the path to executable

    private string GetInstallationPath(string serviceName)
    {
        ServiceController[] services = ServiceController.GetServices();
        foreach (ServiceController service in services)
        {
            if (service.ServiceName == serviceName)
            {
                return service.GetType().Assembly.Location.ToString();
            }
        }
        return string.Empty;
    }

But it does not return the exe exutable path.


Solution

  • AFAIK it can't be done via ServiceController API. You can use WMI:

    var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Service");
    var result = searcher.Get()
        .OfType<ManagementBaseObject>()
        .Select(mo => new
        {
            Name = mo["Name"] as string,
            Path = mo["PathName"] as string
        })
        .ToArray();