简体   繁体   中英

C#: how to collect service only for certain process name by using ServiceController.GetServices()

I am able to get all the process using Process.GetProcesses() under "System.Diagnostics" namespace.

Is there any way to get all the service name within certain process by using "ServiceController.GetServices()"?

foreach (var theProcess in Process.GetProcesses())
            {
                if(theProcess.ProcessName.ToUpper() == "SVCHOST")
                {
                    ServiceController.GetServices().Where(e=>e.)
                }

                //Console.WriteLine("Process: {0} ID: {1}", theProcess.ProcessName, theProcess.Id);
            }

No , there is no way because you have no special attributes or properties . But you can do the same thing using ManagementObjectSearcher

foreach (var theProcess in Process.GetProcesses())
{
    if (theProcess.ProcessName.ToUpper() == "SVCHOST")
    {
        ManagementObjectSearcher mos = new ManagementObjectSearcher("root\\CIMV2", string.Format("SELECT * FROM Win32_Service " + "where ProcessId={0}", theProcess.Id));
        foreach (ManagementObject mo in mos.Get())
        {
            Console.WriteLine("Name: " + mo["Name"]);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM