簡體   English   中英

從資源加載的程序集引發無法加載文件或程序集

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

我正在編寫一個應該創建一些快捷方式的簡單應用程序。 為此,我使用添加為嵌入式資源的Interop.IWshRuntimeLibrary

在課堂上我打電話給

Assembly.Load(Resources.Interop_IWshRuntimeLibrary);

我也嘗試過:

AppDomain.CurrentDomain.Load(Resources.Interop_IWshRuntimeLibrary);

當我在VisualStudio輸出窗口中構建應用程序時,我看到程序集已加載:

加載“ Interop.IWshRuntimeLibrary”。

但是,當我嘗試在該程序集中使用對象時,它給了我這個例外:

“無法加載文件或程序集“ Interop.IWshRuntimeLibrary,版本= 1.0.0.0,區域性=中性,PublicKeyToken =空”。

它不是您想的那么簡單,如果Visualstudio說已加載引用,則意味着在構建過程中已加載了項目的引用。 它與您要實現的目標無關。

最簡單的方法是綁定到程序集解析失敗時調用的AppDomain.AssemblyResolve事件

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM