gpt4 book ai didi

c# - 无法删除通过 C# 中的 Assembly.LoadFrom 加载的文件

转载 作者:行者123 更新时间:2023-11-30 21:04:21 25 4
gpt4 key购买 nike

我正在用 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") 已保存对此文件的引用并且不会丢失它。有什么办法可以解决这个问题吗?

感谢和问候

最佳答案

您需要在另一个应用程序域中加载该类型。通常,这是通过将派生自 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...
...
}
}

关于c# - 无法删除通过 C# 中的 Assembly.LoadFrom 加载的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12458486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com