使用 c# 从服务名称中获取进程 ID [英] Get the process id from the service name using c#

查看:39
本文介绍了使用 c# 从服务名称中获取进程 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

试试这个:

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

这篇关于使用 c# 从服务名称中获取进程 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆