【发布时间】:2022-01-18 03:20:13
【问题描述】:
我尝试重新安装现有服务,但它返回错误“错误 1001。指定的服务已存在”
我尝试了“sc delete servicename”,但它不起作用。对此有何意见?
【问题讨论】:
-
您在尝试删除服务之前是否已停止服务?
我尝试重新安装现有服务,但它返回错误“错误 1001。指定的服务已存在”
我尝试了“sc delete servicename”,但它不起作用。对此有何意见?
【问题讨论】:
在安装/升级/修复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;
}
}
}
【讨论】:
除了 CathalMF 回答之外,我还必须通过在代码中添加以下行来在卸载之前停止服务:
if (s.ServiceName == this.serviceInstaller1.ServiceName)
{
if(s.Status == ServiceControllerStatus.Running)
s.Stop();
....
}
【讨论】: