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

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


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

无法加载文件或程序集“ MyAssembly,版本= 1.0.0.0,区域性=中性,PublicKeyToken =空”或其依赖项之一。该系统找不到指定的文件。

我想加载D:中存在的程序集。为什么需要同时将其副本放入“ bin”目录?

最佳答案

也许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;
}

关于c# - Assembly.LoadFrom()引发异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6555229/

10-10 22:35