我想直接用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)
{
}
}
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>
<identity impersonate= " true " userName= " 服務器登錄名 " password= " 登錄密碼 "/>
</system.web>