**如果需要使用设置完成,请按照下列步骤操作:
这可以通过显式实现现有的服务删除(卸载),然后允许安装更新的版本来处理。 为此,我们需要更新ProjectInstaller.Designer.cs,如下所示:
考虑在InitializeComponent()的开始处添加以下行,这会在当前的安装程序尝试再次安装服务之前触发一个用于卸载现有服务的事件。 这里我们卸载服务,如果它已经存在。
添加以下命名空间:
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 services = new List(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; } } }
PS:随着上述变化,请考虑更新设置版本,产品代码(和可选的升级代码),以便更好的实践,更好的版本管理,跟踪和维护