C# 代码重启windows服务


我想直接用C#代码重启windows服务,经过试验,没有问题,贴出来保存收藏!

 

C#代码:

ServiceController service =  new ServiceController( " EnergyRecordService ");
protected  void btnRestart_Click( object sender, EventArgs e)
    {
         try
        {
             if (service.Status == ServiceControllerStatus.Running)
            {
                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped);
            }
            service.Start();
            service.WaitForStatus(ServiceControllerStatus.Running);

        }
         catch (Exception)
        {
        }
    }

 

Web.Config 配置文件:

如果配置文件不配置这个的话会报一个错误:

Win32Exception (0x80004005): Access is denied 
[InvalidOperationException: Cannot open EnergyRecordService service on computer '.'.]

<system.web> 
 
<identity impersonate= " true " userName= " 服务器登录名 " password= " 登录密码 "/> 
 
</system.web>

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM