错误1001。指定的服务已经存在。现有的服务无法删除。

3

我尝试重新安装现有服务,但返回错误"Error 1001. The specified service already exists(错误1001。指定的服务已存在)"

我尝试使用"sc delete servicename",但没有起作用。对此有什么建议吗?


你在尝试删除服务之前停止了它吗? - Jim Mischel
2个回答

15

我发现解决安装/升级/修复Windows服务项目时遇到的“错误1001.指定的服务已经存在”的最佳方法是修改ProjectInstaller.Designer.cs。

在InitializeComponent()开头添加以下行,这将在当前安装程序尝试重新安装服务之前触发一个事件。在此事件中,如果服务已经存在,我们将卸载该服务。

请确保在cs文件顶部添加以下内容以实现以下命名空间...

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

然后像以下示例中所示使用以下内容...

this.BeforeInstall += new
System.Configuration.Install.InstallEventHandler(ProjectInstaller_BeforeInstall);

例子:

private void InitializeComponent()
{

    this.BeforeInstall += new System.Configuration.Install.InstallEventHandler(ProjectInstaller_BeforeInstall);

    this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
    this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
    // 
    // serviceProcessInstaller1
    // 
    this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
    this.serviceProcessInstaller1.Password = null;
    this.serviceProcessInstaller1.Username = null;
    // 
    // serviceInstaller1
    // 
    this.serviceInstaller1.Description = "This is my service name description";
    this.serviceInstaller1.ServiceName = "MyServiceName";
    this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
    // 
    // ProjectInstaller
    // 
    this.Installers.AddRange(new System.Configuration.Install.Installer[]{
            this.serviceProcessInstaller1,
            this.serviceInstaller1
        }
    );
}
以下代码由事件调用,如果服务存在,则卸载该服务。
void ProjectInstaller_BeforeInstall(object sender, System.Configuration.Install.InstallEventArgs e)
{
    List<ServiceController> services = new List<ServiceController>(ServiceController.GetServices());

    foreach (ServiceController s in services)
    {
        if (s.ServiceName == this.serviceInstaller1.ServiceName)
        {
            ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
            ServiceInstallerObj.Context = new System.Configuration.Install.InstallContext();
            ServiceInstallerObj.Context = Context;
            ServiceInstallerObj.ServiceName = "MyServiceName";
            ServiceInstallerObj.Uninstall(null);

            break;
        }
    }
}

1
我看到你已经编辑了我的答案,但ToList()是Linq的一部分并且可以工作。显然,您需要在项目中使用System.Linq。 - CathalMF
谢谢。这是我见过的关于“错误1001”的最佳答案。 - Orkun Bekar
@CathalMF 你救了我的一天,伙计。我几乎花了两天时间解决这个问题。除了这段代码,我还不得不使用 Orca 从 InstallExecuteSequence 表中删除 InstallValidate 操作。 - Kurubaran
你为什么要设置两次上下文? - Glaucus
不,这是意外的。 - CathalMF
显示剩余4条评论

0
除了CathalMF的答案之外,我还需要在卸载之前添加以下代码行来停止服务:
    if (s.ServiceName == this.serviceInstaller1.ServiceName)
    {
        if(s.Status == ServiceControllerStatus.Running)
           s.Stop();
        ....
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接