代码之家  ›  专栏  ›  技术社区  ›  Ayush

启动和停止服务

c#
  •  2
  • Ayush  · 技术社区  · 15 年前

    在进行这些更改之前,如何以编程方式停止服务,然后重新启动它?

    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);
                }
    
            }
        }
    }
    
    2 回复  |  直到 15 年前
        1
  •  6
  •   Oded    15 年前

    使用 ServiceController 上课。它公开了启动和停止服务的方法,前提是您知道服务的名称。

    ServiceController sc = new ServiceController("Simple Service");
    if (sc.Status == ServiceControllerStatus.Stopped)
    {
      sc.Start();
    }
    
        2
  •  2
  •   openshac    15 年前

    这里有一篇文章向您展示了如何: http://www.csharp-examples.net/restart-windows-service/