给定服务名称(例如SNMPTRAP
)我如何获得System.Diagnostics.Process
个对象?
到目前为止,我找到了System.ServiceProcess.ServiceController类和System.Diagnostics.Process类,但似乎无法从另一个中获得。
答案 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;
}