卸载服务可执行文件后无法删除它

发布于 2024-09-20 00:51:44 字数 431 浏览 2 评论 0原文

我正在卸载这样的服务:

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

工作正常,但随后我尝试执行 Directory.Delete,它会抛出一个异常,表示对该服务的可执行文件的访问被拒绝。但之后,我可以在 Windows 资源管理器中手动删除该文件。

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

有什么想法为什么我无法删除该文件吗?

I'm uninstalling a service like this:

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

which works fine, but then I try to do a Directory.Delete, and it throws an exception saying that access to the service's executable was denied. Yet immediately after, I can delete the file manually in windows explorer.

My application is being run by an installer that requests admin access, so I'm assuming that it has rights to the file. In fact, it deletes all of the other files in that directory, it just can't get that one. I also checked and the file isn't read only.

Any ideas why I can't delete this file?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情未る 2024-09-27 00:51:44

事实证明,该文件有一个保持打开状态的句柄。解决方案是创建一个新的 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, null, null).Unwrap() as AssemblyInstaller)
{
    installer.UseNewContext = true;
    installer.Uninstall(null);
}

AppDomain.Unload(domain);

It turns out that there's a handle to that file that stays open. The solution was to create a new AppDomain, that the installer runs in, and to close it before trying the delete:

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, null, null).Unwrap() as AssemblyInstaller)
{
    installer.UseNewContext = true;
    installer.Uninstall(null);
}

AppDomain.Unload(domain);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文