我创建了一个新的应用程序域并将 2 个程序集加载到其中(参见下面的代码示例)。但是,如果我尝试使用GetAssemblies
方法,我会得到异常System.IO.FileNotFoundException
。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
namespace TestAppDomains
{
class Program
{
static void Main(string[] args)
{
String path = @"D:\PROGRAMMING\ConsoleTest\ConsoleTest\bin\Debug\ConsoleTest.exe";
String pathdll = @"D:\PROGRAMMING\ConsoleTestDll\ConsoleTestDll\bin\Debug\ConsoleTestDll.dll";
AppDomain myDomain1 = AppDomain.CreateDomain("Domain1");
//Create the loader (a proxy).
var assemblyLoader = (SimpleAssemblyLoader)myDomain1.CreateInstanceAndUnwrap(typeof(SimpleAssemblyLoader).Assembly.FullName, typeof(SimpleAssemblyLoader).FullName);
assemblyLoader.LoadFrom(path);
assemblyLoader.LoadFrom(pathdll);
var currentDomainAssemblies = AppDomain.CurrentDomain.GetAssemblies();
var myDomainAssemblies = myDomain1.GetAssemblies(); //There is exception System.IO.FileNotFoundException
Task.Run(() => myDomain1.ExecuteAssembly(path));
//Finally unload the AppDomain.
Console.ReadKey();
AppDomain.Unload(myDomain1);
}
public class SimpleAssemblyLoader : MarshalByRefObject
{
public void Load(string path)
{
ValidatePath(path);
Assembly.Load(path);
}
public void LoadFrom(string path)
{
ValidatePath(path);
Assembly.LoadFrom(path);
}
private void ValidatePath(string path)
{
if (path == null) throw new ArgumentNullException("path");
if (!System.IO.File.Exists(path))
throw new ArgumentException(String.Format("path \"{0}\" does not exist", path));
}
}
}
}