从资源加载的程序集引发无法加载文件或程序集 [英] Assembly loaded from Resources raises Could not load file or assembly

查看:32
本文介绍了从资源加载的程序集引发无法加载文件或程序集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个应该创建一些快捷方式的简单应用程序.为此,我使用了作为嵌入式资源添加的 Interop.IWshRuntimeLibrary.

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

在班级初始化时我调用

Assembly.Load(Resources.Interop_IWshRuntimeLibrary);

我也试过:

AppDomain.CurrentDomain.Load(Resources.Interop_IWshRuntimeLibrary);

当我在 VisualStudio 输出窗口中构建应用程序时,我看到程序集已加载:

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

已加载Interop.IWshRuntimeLibrary".

Loaded "Interop.IWshRuntimeLibrary".

但是,当我尝试使用该程序集中的对象时,它给了我这个异常:

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

无法加载文件或程序集"Interop.IWshRuntimeLibrary,版本=1.0.0.0,文化=中性,PublicKeyToken=null".

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

推荐答案

它并不像你想象的那么简单,如果 Visualstudio 说引用已加载,则意味着项目的引用是在构建期间加载的.这与您想要实现的目标无关.

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.

最简单的方法是绑定到 AppDomain.AssemblyResolve 事件,当程序集解析失败时调用:

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

然后:

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

这篇关于从资源加载的程序集引发无法加载文件或程序集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆