简体   繁体   中英

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:

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.

But i got this error when i compile:

在此处输入图像描述

stream, null.

I asume that the resourceName is incorrect because you get a null stream from GetManifestResourceStream() . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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