Get the process id from the service name using c#

心不动则不痛 提交于 2019-12-23 12:19:44

问题


Is there possibility to get the process id from the service name without using management object in c#? Management object is not working when WMI service is in error state.


回答1:


Hope this will help You.

SELECT ProcessId FROM Win32_Service WHERE Name='MyServiceName'



回答2:


try this:

Process p = new Process();
p.StartInfo.FileName = "sc.exe";
p.StartInfo.Arguments = "queryex \"" + srv_name + "\"";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.Start();
p.WaitForExit();
string output = p.StandardOutput.ReadToEnd();
p.Close();
if (output.IndexOf("SERVICE_NAME") != -1)
{
    bool getPid = false;
    string[] words = output.Split(':');
    foreach (string word in words)
    {
        if (word.IndexOf("PID") != -1 && getPid == false)
        {
            getPid = true;
        }
        else if (getPid == true)
        {
            string[] pid = word.Split('\r');
            return Convert.ToInt32(pid[0]);
        }
    }
}


来源:https://stackoverflow.com/questions/20698194/get-the-process-id-from-the-service-name-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!