如果您希望通过更直观的方式使用WMI
ServiceController
类,参见
this article
(请原谅配色方案,但它有你想要的)。
示例代码(这里的错误处理是按我的口味硬编码的):
using System.Management;
public static ReturnValue StartService(string svcName)
{
string objPath = string.Format("Win32_Service.Name='{0}'", svcName);
using (ManagementObject service = new ManagementObject(new ManagementPath(objPath)))
{
try
{
ManagementBaseObject outParams = service.InvokeMethod("StartService",
null, null);
return (ReturnValue)Enum.Parse(typeof(ReturnValue),
outParams["ReturnValue"].ToString());
}
catch (Exception ex)
{
if (ex.Message.ToLower().Trim() == "not found" ||
ex.GetHashCode() == 41149443)
return ReturnValue.ServiceNotFound;
else
throw ex;
}
}
}