c# 控制服务启动停止

时间:2021-09-16 17:25:02
public string StartService(string serviceName, bool serviceFlag)
        {
            try
            {                
                using (System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(serviceName))
                {                    
                    TimeSpan timeout = new TimeSpan(0, 0, 15);
                    //开
                    if (serviceFlag)
                    {
                        if (sc.Status != ServiceControllerStatus.Running)
                        {
                            sc.Start();
                            sc.WaitForStatus(ServiceControllerStatus.Running, timeout);
                        }
                    }
                    else
                    {
                        if (sc.Status != ServiceControllerStatus.Stopped)
                        {
                            sc.Stop();
                            sc.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                return e.Message;
            }
            var msg="";

            if (serviceFlag)
            { msg = "开启 " + serviceName + "  服务成功"; }
            else
            {
                msg = "关闭 " + serviceName + " 服务成功";
            }
            return msg;

        }

  

 

部署IIS,应用池-高级设置--》标识--》本地系统

c# 控制服务启动停止