C# 使用c从服务名称获取进程id#
是否有可能在不使用c#中的管理对象的情况下从服务名称获取进程id?当WMI服务处于错误状态时,管理对象不工作。希望这对您有所帮助C# 使用c从服务名称获取进程id#,c#,windows-services,C#,Windows Services,是否有可能在不使用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 + "\"";
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]);
}
}
}
这个答案依赖于WMI,但问题明确排除了基于WMI的解决方案。