启动和停止服务

xbo*_*nez 2 c#

我使用以下代码片段来更改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);
            }

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ode*_*ded 6

使用该ServiceController课程.如果您知道其名称,它会公开启动和停止服务的方法.

ServiceController sc = new ServiceController("Simple Service");
if (sc.Status == ServiceControllerStatus.Stopped)
{
  sc.Start();
}
Run Code Online (Sandbox Code Playgroud)