Assembly loaded from Resources raises Could not load file or assembly

你离开我真会死。 提交于 2019-12-11 02:54:18

问题


I am writing a simple application that should create some shortcuts. For this I use Interop.IWshRuntimeLibrary that i add as an Embedded Resource.

On class init I call

Assembly.Load(Resources.Interop_IWshRuntimeLibrary);

I also tried:

AppDomain.CurrentDomain.Load(Resources.Interop_IWshRuntimeLibrary);

When I build the application in VisualStudio Output window I see that the assembly is loaded:

Loaded "Interop.IWshRuntimeLibrary".

But, when I try to use the objects in that assembly it gives me this exception:

"Could not load file or assembly "Interop.IWshRuntimeLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null".


回答1:


It is not so simple as you think and if Visualstudio says that the reference is loaded it means that the references of the project is loaded during build. It has nothing to do with what you are tring to achieve.

the easiest way is to bind to AppDomain.AssemblyResolve Event that is called when the resolution of an assembly fails:

AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

then:

private Assembly MyResolveEventHandler(object sender,ResolveEventArgs args)
{
    Assembly rtn=null;

    //Check for the assembly names that have raised the "AssemblyResolve" event.
    if(args.Name=="YOUR RESOURCE ASSEMBLY NAME")
    {
        //load from resource
        Stream resxStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("YOUR RESOURCE ASSEMBLY NAME");
        byte[] buffer = new byte[resxStream.Length];
        resxStream.Read(buffer, 0, resxStream.Length);
        rtn = Assembly.Load(buffer);
    }
    return rtn;         
}


来源:https://stackoverflow.com/questions/22556258/assembly-loaded-from-resources-raises-could-not-load-file-or-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!