给定服务名称(例如SNMPTRAP
),我如何获取System.Diagnostics.Process
对象?
到目前为止,我已经找到了System.ServiceProcess.ServiceController类和System.Diagnostics.Process类,但似乎无法从另一个中得到一个。
给定服务名称(例如SNMPTRAP
),我如何获取System.Diagnostics.Process
对象?
到目前为止,我已经找到了System.ServiceProcess.ServiceController类和System.Diagnostics.Process类,但似乎无法从另一个中得到一个。
看起来 WMI 无需求助于互操作/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;
}