使用c#从服务名称获取进程ID

是否有可能在不使用c#中的管理对象的情况下从服务名称获取进程ID? 当WMI服务处于错误状态时,管理对象不起作用。

希望这会帮助你。

SELECT ProcessId FROM Win32_Service WHERE Name='MyServiceName' 

试试这个:

 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]); } } }