Dot-Net

安裝帶有恢復操作的 Windows 服務以重新啟動

  • October 27, 2009

我正在使用ServiceProcessInstallerServiceInstaller類安裝 Windows 服務。

我已經使用ServiceProcessInstaller來設置啟動類型、名稱等。但是如何將恢復操作設置為重新啟動?

我知道我可以在安裝服務後手動執行此操作,方法是轉到服務管理控制台並更改服務屬性的恢復選項卡上的設置,但是有沒有辦法在安裝期間執行此操作?

服務屬性恢復選項卡

您可以使用sc設置恢復選項。以下將設置服務在失敗後重新啟動:

sc failure [servicename] reset= 0 actions= restart/60000

這可以很容易地從 C# 呼叫:

static void SetRecoveryOptions(string serviceName)
{
   int exitCode;
   using (var process = new Process())
   {
       var startInfo = process.StartInfo;
       startInfo.FileName = "sc";
       startInfo.WindowStyle = ProcessWindowStyle.Hidden;

       // tell Windows that the service should restart if it fails
       startInfo.Arguments = string.Format("failure \"{0}\" reset= 0 actions= restart/60000", serviceName);

       process.Start();
       process.WaitForExit();

       exitCode = process.ExitCode;
   }

   if (exitCode != 0)
       throw new InvalidOperationException();
}

引用自:https://stackoverflow.com/questions/1633429