2011-07-02 173 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; 
    } 
}