セットアッププロジェクトで作成したセットアップファイルでWindowsサービスの上書きインストールをやる

作成日:
エラー

Visual Studio 2015 のセットアッププロジェクトで作成したインストーラ―でWindowsサービスを上書きインストールすると次のエラーが表示されました。

Error 1001.ソース (サービス名) は既にローカルコンピューターに存在します。
対策

対策ですが、セットアッププロジェクトのカスタム動作に指定している ProjectInstaller.cs の serviceProcessInstaller1 に BeforeInstall イベントを作成し、そこに既存の登録情報を削除する処理を定義しました。

using System.Collections.Generic; 
using System.ServiceProcess; 

private void serviceProcessInstaller1_BeforeInstall(object sender, System.Configuration.Install.InstallEventArgs e)
{
    // 上書きインストール時、上書きできるようにインストール前に既存の登録情報を削除します。
    var services = new List(ServiceController.GetServices());
    foreach (ServiceController s in services)
    {
        if (s.ServiceName == this.serviceInstaller1.ServiceName)
        {
            var serviceInstaller = new ServiceInstaller();
            serviceInstaller.Context = new System.Configuration.Install.InstallContext();
            serviceInstaller.Context = Context;
            serviceInstaller.ServiceName = this.serviceInstaller1.ServiceName;
            serviceInstaller.Uninstall(null);
            break;
        }
    }
}
参考リンク
エラー1001:既に指定されたサービスが存在します。既存のサービスを削除できません
サービスプログラムのインストーラを作る~セットアッププロジェクト(VS2008)→VS2019もOK
C#でWindowsサービス作成その3
関連記事