Assembly.LoadFrom()抛出异常

Dom*_*ang 1 c# reflection

public Assembly LoadAssembly(string assemblyName) //@"D://MyAssembly.dll"

{
    m_assembly = Assembly.LoadFrom(assemblyName);
    return m_assembly;
}
Run Code Online (Sandbox Code Playgroud)

如果我将"MyAssembly.dll"放在D:中并将其副本放在"bin"目录中,则该方法将成功执行.但是,我删除其中任何一个,它会抛出异常.消息如下:

无法加载文件或程序集"MyAssembly,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null"或其依赖项之一.该系统找不到指定的文件.

我想加载D:中存在的组件.为什么我需要同时将其副本放到"bin"目录?

Dev*_*erX 5

也许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;
}
Run Code Online (Sandbox Code Playgroud)