views:

24

answers:

1

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?

+1  A: 

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);
Mike Pateras