**如果需要使用仅安装完成,请按:
这可以通过明确的执行现有的服务中移除(卸载),然后让新版本的安装的处理。 对于这一点,我们需要如下更新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<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;
}
}
}
PS:随着上述变化,也请考虑更新安装版本,产品代码(和optionall的UpgradeCode)为好做法,更好的版本管理,跟踪和维护
要清楚,有一个服务名称和一个服务显示名称。有时候人们会忘记services.msc中的“name”列是服务的显示名称。您通过右键单击您的服务并转到属性来获得服务名称。 – Tung 2012-03-27 18:46:53
@Tung我查过了,他们都是一样的。 – 2012-03-27 18:48:51
迁移到http://www.superuser.com?这不是一个真正的编程问题。 – CodingWithSpike 2012-03-27 20:45:19