【问题标题】:After uninstalling service using AssemblyInstaller I can not delete .exe file使用 AssemblyInstaller 卸载服务后,我无法删除 .exe 文件
【发布时间】:2020-02-24 13:49:04
【问题描述】:

我在代码中使用AssemblyInstaller 删除服务,之后我尝试删除 .exe 文件。

但是发生了错误:

该文件被另一个进程使用。

我试过assemblyInstaller.dispose() 但它不起作用。

using (AssemblyInstaller installer = new AssemblyInstaller(filepath, commandLineOptions))
{
     installer.UseNewContext = true;
     installer.Uninstall(null);
     installer.Dispose();
}

【问题讨论】:

  • 这完全正常,.NET 中的程序集在卸载之前无法删除。这需要卸载使用它的 AppDomain。您几乎可以肯定没有将 AssemblyInstaller 用于其预期用途,这从代码 sn-p 中是不可能看到的。 InstallUtil.exe 通常使用它来卸载/安装服务。除了添加/删除注册表项之外,它没有任何作用。
  • @Hans Passant 我认为 AssemblyInstaller 用于安装和卸载服务。您是否为此建议 InstallUtil?如何从 assemblyinstaller 卸载 appdomain?
  • 是的,这就是 InstallUtil.exe 的本意。它不会导致此问题,因为它在完成其工作后终止,这也消除了组件上的锁定。如果您想自己执行此操作并保持程序运行,那么您必须在 Google 上搜索“c# how to unload an appdomain”。
  • @Hans Passant 感谢您的帮助

标签: c# windows windows-services


【解决方案1】:

使用Resource Monitor 查找进程已打开的文件句柄。找到该进程后,您可以终止它以释放文件句柄,从而允许您将其删除。

【讨论】:

  • 你的意思是什么?你还在创建文件并打开文件句柄?
  • 运行服务时,它会将文件加载到内存中。操作系统记录谁拥有文件句柄的所有权。在资源监视器中搜索文件以查找使句柄保持打开状态的进程。你不明白什么?
【解决方案2】:

在其他人的帮助下,我发现使用 AssemblyInstaller 会导致问题。要卸载服务,我们可以使用其他方法,例如 InstallUtil.exe 或 ServiceInstaller。我们可以用ServiceInstaller代替AssemblyInstaller来卸载,不会出现这个问题。

 ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
 InstallContext Context = new InstallContext(AppDomain.CurrentDomain.BaseDirectory + "\\uninstalllog.log", null);
 ServiceInstallerObj.Context = Context;
 ServiceInstallerObj.ServiceName = "myService";
 ServiceInstallerObj.Uninstall(null);

这将删除服务指定名称,并且可以毫无问题地删除 .exe 文件

编辑

我发现使用AppDomain我们可以卸载程序集

var domain = AppDomain.CreateDomain("MyDomain");
            using (AssemblyInstaller installer = domain.CreateInstance(typeof(AssemblyInstaller).Assembly.FullName, typeof(AssemblyInstaller).FullName, false, BindingFlags.Public | BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.ExactBinding, null, new Object[] { servicePath, new String[] { } }, null, null, null).Unwrap() as AssemblyInstaller)
            {
                installer.UseNewContext = true;
                installer.Uninstall(null);
            }
            AppDomain.Unload(domain);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    • 1970-01-01
    • 2013-12-10
    • 1970-01-01
    • 2021-07-12
    相关资源
    最近更新 更多