开发者

Assembly.LoadFrom() throw exception

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

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

If I put "MyAssembly.dll" both in D: and its copy in "bin" directory, the method will excute successfully. However, I delete any one of them, it will throw exception. Message like below:

Could not load file or assembly 'MyAssembly, Version=1.0.0.0, Cult开发者_如何学Goure=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

I wanna load the assembly which exists in D:. why I need put its copy to "bin" directory at the same time?


Maybe MyAssembly.dll refers to some assembly that arent in the directory. Put all assemblies in the same directory.

Or you can handle AppDomain.CurrentDomain, AssemblyResolve event to load the needed assembly

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


To get any specific exceptions you could try this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜