C # - «ошибка 1001» - указанная служба уже существует. Как удалить сервис? - PullRequest
1 голос
/ 08 ноября 2019

У меня есть установщик проекта, который устанавливает службу Windows.
Когда я создаю новую версию, мне нужно удалить ее и установить новую версию.
Пожалуйста, проверьте код ниже:

private void InitializeComponent()
{
    this.ServiceProcessInstaller = new System.ServiceProcess.ServiceProcessInstaller();
    this.MyServiceInstaller = new System.ServiceProcess.ServiceInstaller();
    // 
    // ServiceProcessInstaller
    // 
    this.ServiceProcessInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
    this.ServiceProcessInstaller.Password = null;
    this.ServiceProcessInstaller.Username = null;
    this.ServiceProcessInstaller.BeforeInstall += new System.Configuration.Install.InstallEventHandler(this.BeforeInstall);
    // 
    // MyServiceInstaller
    // 
    this.MyServiceInstaller.Description = "Description";
    this.MyServiceInstaller.ServiceName = "My Service";
    // 
    // ProjectInstaller
    // 
    this.Installers.AddRange(new System.Configuration.Install.Installer[] {
    this.ServiceProcessInstaller,
    this.MyServiceInstaller});

}


void BeforeInstall(object sender, System.Configuration.Install.InstallEventArgs e)
{
    List<ServiceController> services = new List<ServiceController>(ServiceController.GetServices());

    foreach (ServiceController s in services)
    {
        if (s.ServiceName == "My Service")
        {
            ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
            ServiceInstallerObj.Context = new InstallContext();
            ServiceInstallerObj.ServiceName = "My Service";
            ServiceInstallerObj.Uninstall(null);

            break;
        }
    }
}

Я установил событие BeforeInstall, но снова получил ошибку 1001.


...