Failed to delete the service executable after deleting it.

I will remove the following service:

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

which works fine, but then I try to do Directory.Delete, and it throws an exception saying that access to the service executable was denied. However, right after that, I can delete the file manually in Windows Explorer.

My application is launched by the installer, which asks for administrator access, so I assume that it has file permissions. In fact, it deletes all other files in this directory; it simply cannot receive it. I also checked and the file is not readable.

Any ideas why I cannot delete this file?

+4
source share
1 answer

It turns out there is a handle to this file that remains open. The solution was to create a new AppDomain that the installer launches, and close it before trying to uninstall:

 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); 
+3
source

All Articles