Monday, September 9, 2019

Include dll Reference in Standalone exe for Visual Studio

If you want to build referenced .dll files into your exe so that you can end up with a standalone exe, follow these steps:

Copy the .dll file(s) to somewhere inside your project and include them
Make sure it is set as an Embedded Resource
In the project properties, Resources tab, add existing resource
Select the .dll that you included in the first step
Add the the .dll as a reference
Set Copy Local to false
In the code for the Form, insert the following code so that it executes before InitializeComponent()

AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { string resourceName = new AssemblyName(args.Name).Name + ".dll"; string resource = Array.Find(this.GetType().Assembly.GetManifestResourceNames(), element => element.EndsWith(resourceName)); using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource)) { Byte[] assemblyData = new Byte[stream.Length]; stream.Read(assemblyData, 0, assemblyData.Length); return Assembly.Load(assemblyData); } };

You may need to add using System.Reflection; to your form for that code to work.