2011-07-02 176 views
0
public Assembly LoadAssembly(string assemblyName) //@"D://MyAssembly.dll" 

{ 
    m_assembly = Assembly.LoadFrom(assemblyName); 
    return m_assembly; 
} 

如果我把「MyAssembly.dll」放在D:及其拷貝到「bin」目錄下,該方法會成功執行。但是,我刪除它們中的任何一個,它都會拋出異常。消息如下:Assembly.LoadFrom()拋出異常

無法加載文件或程序集'MyAssembly,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'或其依賴項之一。該系統找不到指定的文件。

我想加載D:中存在的程序集。爲什麼我需要將其副本同時放入「bin」目錄?

回答

4

也許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; 
} 
+0

對不起,我得到了一些錯誤。 在上面的代碼中沒問題,此處顯示異常: 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方法中成功加載,但在調用方拋出異常。 –

+0

我認爲這個異常出現的原因是我將程序集從AppDomain轉移到了另一個AppDomain。 –

+0

http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/70ad4fcd-531d-4494-a9bb-1684d8b3f3ec/ –

1

要在任何特定的例外情況,你可以試試這個:

try 
{ 
    return Assembly.LoadFrom(assemblyName); 
} 
catch (Exception ex) 
{ 
    var reflection = ex as ReflectionTypeLoadException; 

    if (reflection != null) 
    { 
     foreach (var exception in reflection.LoaderExceptions) 
     { 
      // log/inspect the message 
     } 

     return null; 
    } 
}