c# - 从资源加载的程序集引发无法加载文件或程序集

标签 c# .net reflection .net-assembly embedded-resource

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

在类初始化时我调用

Assembly.Load(Resources.Interop_IWshRuntimeLibrary);

我也尝试过:

AppDomain.CurrentDomain.Load(Resources.Interop_IWshRuntimeLibrary);

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

Loaded "Interop.IWshRuntimeLibrary".

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

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

最佳答案

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

最简单的方法是绑定(bind)到 AppDomain.AssemblyResolve Event当程序集解析失败时调用:

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

关于c# - 从资源加载的程序集引发无法加载文件或程序集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22556258/

相关文章:

c# - C# 中的 LINQ 查询使用动态字符串来 ORDER 数据

c# - 如何用简单的注入(inject)器注入(inject)

c# - 将大型 MFC 应用程序迁移到 WPF/.NET 有哪些技术?

c# - 使用 C# 正则表达式解析 Linux df 输出

c# - 连接特殊字符 "-"的相邻字符

c# - 将日期时间转换为时间跨度

ruby - Ruby 中有没有办法打印出对象的公共(public)方法

c# - 满足开放/封闭原则的工厂模式?

c# - OleDb 连接打开时出现 SEHException

c# - 如何从 pem 文件或 xml 文件中读取 RSA 公钥