简体   繁体   English

C# 如何嵌入和引用外部程序集 (DLL)

[英]C# How To Embed And Reference An External Assembly (DLL)

Im trying to embed one DLL files to my main application(.exe) Here is my program.cs snippet:我试图将一个 DLL 文件嵌入到我的主应用程序 (.exe) 这是我的 program.cs 片段:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Reflection;

namespace testapp
{


static class Program
{
    public static string versioncode = "2";
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);


        AppDomain.CurrentDomain.AssemblyResolve += (Object sender, ResolveEventArgs args) =>
        {
            String thisExe = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
            System.Reflection.AssemblyName embeddedAssembly = new System.Reflection.AssemblyName(args.Name);
            String resourceName = thisExe + "." + embeddedAssembly.Name + ".dll";

            using (var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
            {
                Byte[] assemblyData = new Byte[stream.Length];
                stream.Read(assemblyData, 0, assemblyData.Length);
                return System.Reflection.Assembly.Load(assemblyData);
            }
        };

        Application.Run(new Form1());
    }
}

} }

I am trying to embed DLL named as "ThirdDemo.dll", already added as reference and Copy Local=false also i add as a additional file not just a reference and Build Action=Embedded Resource.我正在尝试嵌入名为“ThirdDemo.dll”的 DLL,已添加为参考和 Copy Local=false 我还添加为附加文件,而不仅仅是参考和 Build Action=Embedded Resource。

But i got this error when i compile:但是我在编译时遇到了这个错误:

在此处输入图像描述

stream, null. stream、null。

I asume that the resourceName is incorrect because you get a null stream from GetManifestResourceStream() .我认为resourceName不正确,因为您从GetManifestResourceStream()获得了 null stream 。 This normally happens if you try to load a resource that does not exist.如果您尝试加载不存在的资源,通常会发生这种情况。

You could use something like ILspy ( https://github.com/icsharpcode/ILSpy/releases ) to open your compiled.exe and lookup the correct name of your embedded resource.您可以使用 ILspy ( https://github.com/icsharpcode/ILSpy/releases ) 之类的东西打开您的 compiled.exe 并查找嵌入式资源的正确名称。

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

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