简体   繁体   中英

Cannot delete file loaded through Assembly.LoadFrom in C#

I am creating an uninstall utility in C#. The utility will unregistered the files registered through Regasm and then it will delete those files.

Assembly asm = Assembly.LoadFrom("c:\\Test.dll")
int count = files.Length;
RegistrationServices regAsm = new RegistrationServices();
if (regAsm.UnregisterAssembly(asm))
MessageBox.Show("Unregistered Successfully");

The above code works fine but when i try to delete Test.dll, error appear and cannot delete it. What i have understand that Assembly.LoadFrom("c:\\Test.dll"), has save the reference to this file and it is not losing it. Is there any way to resolve this issue?

Thanks and Regards

You need to load the type in another appdomain. Typically this is done by loading a type derived from MarshalByRefObject into another domain, marshaling the instance to the original domain and executing the method via proxy. It sounds harder then it is so here is the exampe:

public class Helper : MarshalByRefObject // must inherit MBRO, so it can be "remoted"
{
    public void RegisterAssembly()
    {
      // load your assembly here and do what you need to do
      var asm = Assembly.LoadFrom("c:\\test.dll", null);
      // do whatever...
    }
}

static class Program
{
    static void Main()
    {
      // setup and create a new appdomain with shadowcopying
      AppDomainSetup setup = new AppDomainSetup();
      setup.ShadowCopyFiles = "true";
      var domain = AppDomain.CreateDomain("loader", null, setup);

      // instantiate a helper object derived from MarshalByRefObject in other domain
      var handle = domain.CreateInstanceFrom(Assembly.GetExecutingAssembly().Location, typeof (Helper).FullName);

      // unwrap it - this creates a proxy to Helper instance in another domain
      var h = (Helper)handle.Unwrap();
      // and run your method
      h.RegisterAssembly();
      AppDomain.Unload(domain); // strictly speaking, this is not required, but...
      ...
    }
}

You cannot unload any Assembly that is loaded. Shadow copying , or loading assembly into another domain is what will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM