Search code examples
c#cmdwindows-servicesexecutable-path

How to find executable path of a windows service


I am trying to find the executable path of a running service , and i have looked upon ServiceBase and there is no property indicating the path. Nor does ServiceController offer any kind of help.

ServiceBase []services=ServiceController.GetServices();
IEnumerable<string> paths=services.Select(x=> x. ? );

I have also tried using sc qc cmd command but it seems it does not work for a particular service

            Process proc = new Process();
            var info = new ProcessStartInfo();
            info.FileName = "cmd.exe";
            info.Arguments = "sc qc \"[service-name]\" | find \"BINARY_PATH_NAME\"";
            proc.StartInfo = info;
            proc.Start();
            var data = await proc.StandardOutput.ReadToEndAsync();

It throws the error:

System.InvalidOperationException: 'StandardOut has not been redirected or the process hasn't started yet.'

Is there any way to get the path of the executable for a particular service or all of them ?


Solution

  • You can use WMI

    For example (with WMI Code Creator):

                try
                {
                    ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Service");
                    foreach (ManagementObject queryObj in searcher.Get())
                    {
                        Console.WriteLine("DisplayName: {0}", queryObj["DisplayName"]);
                        Console.WriteLine("Name: {0}", queryObj["Name"]);
                        Console.WriteLine("PathName: {0}", queryObj["PathName"]);
                        Console.WriteLine("ProcessId: {0}", queryObj["ProcessId"]);
                        Console.WriteLine("-----------------------------------");
                    }
                }
                catch (ManagementException me)
                {
                    MessageBox.Show("An error occurred while querying for WMI data: " + me.Message);
                }