2010-10-15 67 views
1

如何使用WMI從.NET代碼啓動,停止和查詢本地計算機上的服務? (我正在使用C#)如何使用.NET中的WMI啓動和停止服務?

我發現good and accurate answers使用ServiceController類來做到這一點,但我想如果可以的話使用WMI。

+1

*能* WMI做到這一點?使用ServiceController類有問題嗎?當然WMI可以告訴你一個服務是一個正在執行的進程 - 從那裏你可以開始()/終止()流程,但是這似乎是你跳過一個完全明顯的抽象層,通過選擇不使用ServiceController類。注意:如果我在這裏可怕的錯誤,請糾正我! – 2010-10-15 00:36:24

+0

@ nathan-taylor,你說得對,ServiceController要乾淨得多,我可能會在後期切換到這個狀態。 – Boinst 2010-10-15 02:12:43

回答

4

如果您希望在更直觀的ServiceController類中使用WMI,請參見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; 
     } 
    } 
} 
+0

感謝Steve,CodeProject上的代碼完全符合我的要求。 – Boinst 2010-10-15 02:10:36