windows-services – 卸载后无法删除服务可执行文件

前端之家收集整理的这篇文章主要介绍了windows-services – 卸载后无法删除服务可执行文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在卸载这样的服务:

using (AssemblyInstaller installer = new AssemblyInstaller(serviceFileName,new String[] { }))
{
    installer.UseNewContext = true;
    installer.Uninstall(null);
}

哪个工作正常,但后来我尝试做一个Directory.Delete,它抛出一个异常,说拒绝访问服务的可执行文件.不久之后,我可以在Windows资源管理器中手动删除文件.

我的应用程序由请求管理员访问权限的安装程序运行,因此我假设它拥有该文件的权限.实际上,它删除了该目录中的所有其他文件,它只是无法获取文件.我也检查过,文件不是只读的.

有什么想法我无法删除这个文件

解决方法

事实证明,该文件的句柄保持打开状态.解决方案是创建一个安装程序运行的新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[] { serviceFileName,new String[] { } },null).Unwrap() as AssemblyInstaller)
{
    installer.UseNewContext = true;
    installer.Uninstall(null);
}

AppDomain.Unload(domain);

猜你在找的Windows相关文章