.NET:如何获取Process对象,给定服务名称?

时间:2012-09-13 13:33:04

标签: .net service process system.diagnostics

给定服务名称(例如SNMPTRAP)我如何获得System.Diagnostics.Process个对象?

到目前为止,我找到了System.ServiceProcess.ServiceController类和System.Diagnostics.Process类,但似乎无法从另一个中获得。

1 个答案:

答案 0 :(得分:2)

看起来WMI无需借助interop / Win32即可运行。以下是概念验证:

    private static Process ProcessFromServiceName(string serviceName)
    {
        // Note abuse of foreach as a lazy way of getting first item.
        // Also assumes that the first service in the collection is the correct one.

        string queryText = String.Format(   CultureInfo.InvariantCulture,
                                            "SELECT * FROM Win32_Service WHERE Name='{0}'",
                                            serviceName);
        var query = new SelectQuery(queryText);
        var searcher = new ManagementObjectSearcher(query);
        foreach (ManagementObject service in searcher.Get())
        {
            int processId = (int)(uint)service.Properties["ProcessId"].Value;
            Process process = Process.GetProcessById(processId);
            return process;
        }
        return null;
    }