也許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/ –