繁体   English   中英

Assembly.LoadFrom() 抛出异常

[英]Assembly.LoadFrom() throw exception

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

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

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

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

我想加载存在于 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;
}

要获得任何特定异常,您可以尝试以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM