问题
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