【问题标题】:Assembly loaded from Resources raises Could not load file or assembly从资源加载的程序集引发无法加载文件或程序集
【发布时间】:2014-03-21 10:31:06
【问题描述】:

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

在类初始化时我调用

Assembly.Load(Resources.Interop_IWshRuntimeLibrary);

我也试过了:

AppDomain.CurrentDomain.Load(Resources.Interop_IWshRuntimeLibrary);

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

已加载“Interop.IWshRuntimeLibrary”。

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

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

【问题讨论】:

  • 这很正常,Assembly.Load(byte[]) 是一种非常糟糕的加载程序集的方式,它没有加载上下文。对于互操作程序集,这是很久以前修复的,只需在程序集引用上将“嵌入互操作类型”设置为 true。您不再需要部署程序集。在那个 COM 组件中也没有什么是您在 .NET 中无法做到的。

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


【解决方案1】:

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

最简单的方法是绑定到在程序集解析失败时调用的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;         
}

【讨论】:

  • @Andrey :D 乐于助人!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-17
相关资源
最近更新 更多