我尝试重新安装现有服务,但返回错误"Error 1001. The specified service already exists(错误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;
}
}
}
if (s.ServiceName == this.serviceInstaller1.ServiceName)
{
if(s.Status == ServiceControllerStatus.Running)
s.Stop();
....
}