简体   繁体   English

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

[英]Assembly loaded from Resources raises Could not load file or assembly

I am writing a simple application that should create some shortcuts. 我正在编写一个应该创建一些快捷方式的简单应用程序。 For this I use Interop.IWshRuntimeLibrary that i add as an Embedded Resource. 为此,我使用添加为嵌入式资源的Interop.IWshRuntimeLibrary

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: 当我在VisualStudio输出窗口中构建应用程序时,我看到程序集已加载:

Loaded "Interop.IWshRuntimeLibrary". 加载“ 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". “无法加载文件或程序集“ Interop.IWshRuntimeLibrary,版本= 1.0.0.0,区域性=中性,PublicKeyToken =空”。

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. 它不是您想的那么简单,如果Visualstudio说已加载引用,则意味着在构建过程中已加载了项目的引用。 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.AssemblyResolve事件

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM