2010-10-25 293 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(); 
}