Home > Software engineering >  How to retrieve the path to executables from services.msc using c#?
How to retrieve the path to executables from services.msc using c#?

Time:01-29

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.

CodePudding user response:

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();
  • Related