我有一个服务。我刚才安装了它。我需要对服务进行更新。我去了添加/删除程序并查找我的服务,但它没有安装在那里。我查看了 services.msc,它就在那里,停止了。我能够启动和停止它。我以管理员身份运行命令提示符并运行 sc delete [Service Name],并收到“指定的服务不作为已安装的服务存在”。我在命令提示符下执行了 sc 查询,但没有返回。我右键单击安装程序,单击卸载并收到“此操作仅对当前安装的产品有效”。我也尝试修复,并收到相同的消息。
我已经重启了几次机器,但没有成功卸载这个服务。我正在使用随 Visual Studio 安装的基本安装项目模板。我试过更改程序的名称,并增加版本号。
如何卸载明显存在的服务,并防止将来发生这种情况?
最佳答案
** 如果需要仅使用设置完成,请遵循:
这可以通过显式实现现有服务删除(卸载)然后允许安装更新版本来处理。 为此,我们需要更新 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:除上述更改外,还请考虑更新设置版本、ProductCode(和可选的 UpgradeCode)以获得良好实践、更好的版本管理、跟踪和维护
关于c# - 错误 1001 : The Specified Service Already Exists. 无法删除现有服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9895586/