Assembly loaded from Resources raises Could not lo

2019-07-16 21:48发布

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条回答
倾城 Initia
2楼-- · 2019-07-16 21:51

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;         
}
查看更多
登录 后发表回答