2

我尝试重新安装现有服务,但它返回错误“错误 1001。指定的服务已存在”

我已经尝试过“sc delete servicename”,但它不起作用。对此有任何意见吗?

4

2 回答 2

14

在安装/升级/修复 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;
        }
    }
}
于 2014-02-08T22:53:14.310 回答
0

除了 CathalMF 回答之外,我还必须通过在代码中添加以下行来在卸载之前停止服务:

    if (s.ServiceName == this.serviceInstaller1.ServiceName)
    {
        if(s.Status == ServiceControllerStatus.Running)
           s.Stop();
        ....
    }
于 2022-01-17T11:39:44.823 回答