首页 > 解决方案 > 通过c#卸载windows服务后无法删除.exe文件

问题描述

我正在使用System.Configuration.Install.ManagedInstallerClass.InstallHelper在另一个服务中安装和卸载 Windows 服务。问题是安装服务时,exe服务被锁定或其他问题,但我需要在服务卸载后删除服务文件。

服务安装:

System.Configuration
      .Install
      .ManagedInstallerClass
      .InstallHelper(new string[] { "/i", serviceExePath });

服务卸载:

System.Configuration
      .Install
      .ManagedInstallerClass
      .InstallHelper(new string[] { "/u", serviceExePath });

尝试删除exe时的错误描述

标签: c#windows-services

解决方案


我遇到了同样的问题。事实证明,在ManageInstallerClass服务上放置了一个文件句柄锁,并且在锁定过程终止之前您无法删除它。
我使用以下代码解决了这个问题:

    var s = new ServiceInstaller
    {
        Context = new InstallContext(),
        ServiceName = "<YOUR SERVICE NAME>"
    };
    s.Uninstall(null);

完成后,ServiceInstaller您应该能够删除服务文件。

要使用,ServiceInstaller您必须将其包含System.ServiceProcess在您的课程中。


推荐阅读