通过 c# 卸载 windows 服务后无法删除 .exe 文件

Unable to delete .exe file after uninstalling windows service through c#

我正在使用 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 });

Error description while trying to delete exe

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

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

ServiceInstaller 完成后,您应该可以删除服务文件。

要使用 ServiceInstaller,您必须在 class 中包含 System.ServiceProcess