将 DLL 程序集从 C# 中的文件加载到自定义应用程序域

本文关键字:加载 文件 自定义 应用程序域 DLL 程序集 | 更新日期: 2023-09-27 18:34:12

我尝试了下一个代码:

AppDomain ad = AppDomain.CreateDomain("Test");      
_Assembly = parDomain.Load(AssemblyName.GetAssemblyName(@"C:'SomeDLLPath'PhysicsTest.dll"));
// Some work with assembly
AppDomain.Unload(ad);

它提高了FileNotFoundException that cannot load file or assembly "TestClass, Version=1.0.0.0, ..."

如果我将程序集加载到此域都可以:

_Assembly = Assembly.LoadFile(@"C:'SomeDLLPath'PhysicsTest.dll");

但我也需要卸载它。

我看到了很多关于它的线程,但无法理解它们......

将 DLL 程序集从 C# 中的文件加载到自定义应用程序域

来自MSDN

块引用

如果不卸载包含

单个程序集的所有应用程序域,就无法卸载该程序集。即使程序集超出范围,实际的程序集文件也将保持加载状态,直到卸载包含它的所有应用程序域。

以下是卸载应用程序域 MSDN 的方法

using System;
using System.Reflection;
class AppDomain2
{
    public static void Main()
    {
        Console.WriteLine("Creating new AppDomain.");
        AppDomain domain = AppDomain.CreateDomain("MyDomain", null);
        Console.WriteLine("Host domain: " + AppDomain.CurrentDomain.FriendlyName);
        Console.WriteLine("child domain: " + domain.FriendlyName);
        AppDomain.Unload(domain);
        try
        {
            Console.WriteLine();
            Console.WriteLine("Host domain: " + AppDomain.CurrentDomain.FriendlyName);
            // The following statement creates an exception because the domain no longer exists.
            Console.WriteLine("child domain: " + domain.FriendlyName);
        }
        catch (AppDomainUnloadedException e)
        {
            Console.WriteLine(e.GetType().FullName);
            Console.WriteLine("The appdomain MyDomain does not exist.");
        }
    }
}