也许MyAssembly.dll引用了一些不在目录中的程序集。把所有的程序集放在同一个目录下。
或者你可以处理AppDomain.CurrentDomain,AssemblyResolve事件加载所需的装配
private string asmBase ;
public void LoaddAssembly(string assemblyName)
{
asmBase = System.IO.Path.GetDirectoryName(assemblyName);
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
System.Reflection.Assembly asm = System.Reflection.Assembly.Load(System.IO.File.ReadAllBytes(assemblyName));
}
private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
//This handler is called only when the common language runtime tries to bind to the assembly and fails.
//Retrieve the list of referenced assemblies in an array of AssemblyName.
Assembly MyAssembly, objExecutingAssemblies;
string strTempAssmbPath = "";
objExecutingAssemblies = args.RequestingAssembly;
AssemblyName[] arrReferencedAssmbNames = objExecutingAssemblies.GetReferencedAssemblies();
//Loop through the array of referenced assembly names.
foreach (AssemblyName strAssmbName in arrReferencedAssmbNames)
{
//Check for the assembly names that have raised the "AssemblyResolve" event.
if (strAssmbName.FullName.Substring(0, strAssmbName.FullName.IndexOf(",")) == args.Name.Substring(0, args.Name.IndexOf(",")))
{
//Build the path of the assembly from where it has to be loaded.
strTempAssmbPath = asmBase + "\\" + args.Name.Substring(0, args.Name.IndexOf(",")) + ".dll";
break;
}
}
//Load the assembly from the specified path.
MyAssembly = Assembly.LoadFrom(strTempAssmbPath);
//Return the loaded assembly.
return MyAssembly;
}
对不起,我得到了一些错误。 在上面的代码中没问题,此处显示异常: AppDomain domain = AppDomain.CreateDomain(“NewDomain”,null,appDomainSetup); Loader =(Loader)domain.CreateInstanceFromAndUnwrap(@“C:\\ Loader.dll”,“Loader.Loader”); assembly = Loader.LoadAssembly(@“D://MyAssembly.dll”); 例外是最后一行。我正在加载新的AppDomain中的.dll文件。 该程序集在LoadAssembly方法中成功加载,但在调用方抛出异常。 –
我认为这个异常出现的原因是我将程序集从AppDomain转移到了另一个AppDomain。 –
http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/70ad4fcd-531d-4494-a9bb-1684d8b3f3ec/ –