用代码启动和停止Windows服务

不废话,直接上代码

using System.ServiceProcess;    
    
	private bool StopWindowsService(string servicename)
        {
            bool result = false;
            ServiceController[] scs = null;
            try
            {
                scs = ServiceController.GetServices();
                foreach (ServiceController sc in scs)
                {
                    if (sc.DisplayName == servicename)
                    {
                        if (sc.Status != ServiceControllerStatus.StopPending && sc.Status != ServiceControllerStatus.Stopped)
                            sc.Stop();
                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                result = false;
                throw ex;
            }

            return result;
        }

        private bool StartWindowsService(string servicename)
        {
            bool result = false;
            ServiceController[] scs = null;
            try
            {
                scs = ServiceController.GetServices();
                foreach (ServiceController sc in scs)
                {
                    if (sc.DisplayName == servicename)
                    {
                        if (sc.Status != ServiceControllerStatus.StartPending && sc.Status != ServiceControllerStatus.Running)
                            sc.Start();
                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                result = false;
                throw ex;
            }

            return result;
        }


你可能感兴趣的:(DotNet)