Reputation: 61
I tried to re-install my existing service and it returns an error "Error 1001. The specified service already exists"
I have tried the "sc delete servicename" but it does not work. Any inputs on this?
Upvotes: 3
Views: 6648
Reputation: 23
In addition to CathalMF answer, I also had to stop the service before uninstall by adding the line below to the code:
if (s.ServiceName == this.serviceInstaller1.ServiceName)
{
if(s.Status == ServiceControllerStatus.Running)
s.Stop();
....
}
Upvotes: 0
Reputation: 10055
The best solution I have found to "Error 1001. The specified service already exists" when installing/upgrading/repairing a Windows Service project is to modify the ProjectInstaller.Designer.cs.
Add the following line to the beginning of InitializeComponent() which will trigger an event before your current installer tries to install the service again. In this event we will uninstall the service if it already exists.
Be sure to add the following to the top of the cs file to implement the following namespaces...
using System.Collections.Generic;
using System.ServiceProcess;
Then use the following as show below in the example...
this.BeforeInstall += new
System.Configuration.Install.InstallEventHandler(ProjectInstaller_BeforeInstall);
Example:
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
}
);
}
The below code called by the event will then uninstall the service if it exists.
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;
}
}
}
Upvotes: 15