我正在用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”)已保存对该文件的引用,并且它没有丢失它。有什么方法可以解决这个问题吗?
谢谢和问候
答案 0 :(得分:3)
您需要在另一个应用程序域中加载该类型。通常,这是通过将从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...
...
}
}
答案 1 :(得分:1)
您无法卸载任何已加载的程序集。 Shadow copying,或将程序集加载到另一个域中可以帮助您。