Mik*_*ras 4 windows-services file-access delete-file
我正在卸载这样的服务:
using (AssemblyInstaller installer = new AssemblyInstaller(serviceFileName, new String[] { }))
{
installer.UseNewContext = true;
installer.Uninstall(null);
}
Run Code Online (Sandbox Code Playgroud)
工作正常,但后来我尝试执行 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, null, null).Unwrap() as AssemblyInstaller)
{
installer.UseNewContext = true;
installer.Uninstall(null);
}
AppDomain.Unload(domain);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
753 次 |
| 最近记录: |