2010-10-25 229 views
2

我正在使用以下代碼片段來更改Windows服務的帳戶和密碼憑據。但是,這隻有在服務停止時纔有效。啓動和停止服務

如何以編程方式在進行這些更改之前停止服務,然後重新啓動它?

namespace ServiceAccount 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string serviceName = "DummyService"; 
      string username = ".\\Service_Test"; 
      string password = "Password1"; 

      string objPath = string.Format("Win32_Service.Name='{0}'", serviceName); 
      using (ManagementObject service = new ManagementObject(new ManagementPath(objPath))) 
      { 
       object[] wmiParams = new object[11]; 
       wmiParams[6] = username; 
       wmiParams[7] = password; 
       service.InvokeMethod("Change", wmiParams); 
      } 

     } 
    } 
} 

回答

6

使用ServiceController類。它提供了啓動和停止服務的方法,只要知道它的名稱即可。

ServiceController sc = new ServiceController("Simple Service"); 
if (sc.Status == ServiceControllerStatus.Stopped) 
{ 
    sc.Start(); 
}