'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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | djv |

