2

我正在 C# 中创建一个卸载实用程序。该实用程序将注销通过 Regasm 注册的文件,然后删除这些文件。

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

上面的代码工作正常,但是当我尝试删除 Test.dll 时,出现错误并且无法删除它。据我所知,Assembly.LoadFrom("c:\Test.dll") 已经保存了对该文件的引用并且没有丢失它。有没有办法解决这个问题?

谢谢并恭祝安康

4

2 回答 2

3

您需要在另一个 appdomain 中加载该类型。通常这是通过将派生自 MarshalByRefObject 的类型加载到另一个域中,将实例编组到原始域并通过代理执行方法来完成的。这听起来更难,所以这里是例子:

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...
      ...
    }
}
于 2012-09-17T12:44:31.713 回答
1

您不能卸载任何已加载的程序集。影子复制或将程序集加载到另一个域对您有帮助。

于 2012-09-17T11:47:19.587 回答