In an ordinary way, when we added a reference of a custom built or third party DLL, it will be distributed along with our main EXE application at the same folder. If the DLL is not existed in the same folder with the EXE application, an exception will be thrown. There are some cases that we wish to pack / include the DLL within the EXE application. Therefore, this article introduces a solution of loading DLLs from embedded resources.
Example of Exception (DLL is not found at the same folder of distributed EXE Application):
Merging DLLs is commonly used in developing portable software.
Advantages
Disadvantages
Embedding DLLs has the same concept of most software installer. Most of the installer are packed into one single file. The reason of this is cut down complexity and make it more easier to distribute.
Basic intro about DLLs used as examples in this article.
Before any coding started, the DLLs have to be added into the project.
First, add the DLL as Reference.
Then, add the same DLL as file into the project. Right click the project's name > Add > Existing Item...
The same DLL will exist twice in different folder in the project.
As the below picture shown,
for Referenced DLL, in the properties explorer, change
= Copy Local
False
for Added DLL as File, in the properties explorer, change Build Action
= Embedded Resource
Do the same thing to System.Data.SQLite.DLL. Add it into project's file and as reference. Change the properties as System.Windows.Forms.Ribbon35.DLL.
Note: If you have any other unmanaged / native DLL that is not able to be referenced, then you won't have to reference it, just add the Unmanaged DLL as embedded resource.
Obtain EmbeddedAssembly.cs from download and add it into project.
or browse to bottom of this article and copy the code of EmbeddedAssembly.cs.
Open Program.cs
Initial code of Program.cs
static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } }
Load the DLL from Embedded Resource into Memory. Use EmbeddedAssembly.Load
to load it into memory.
static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { string resource1 = "MyApp.System.Windows.Forms.Ribbon35.dll"; string resource2 = "MyApp.System.Data.SQLite.dll"; EmbeddedAssembly.Load(resource1, "System.Windows.Forms.Ribbon35.dll"); EmbeddedAssembly.Load(resource2, "System.Data.SQLite.dll"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } }
Take note about the format of the resource string. Example:
MyApp.System.Windows.Forms.Ribbon35.dll
This string is the Embedded Resource address in the project.
MyApp
is the project name, followed by the DLL filename. If the DLL is added inside a folder, the folder's name must be included in the resource string. Example:
MyApp.NewFolder1.System.Windows.Forms.Ribbon35.dll
The DLLs are not distributed with the application, when the application fails to locate the DLL, it raises an Event of AppDomain.CurrentDomain.AssemblyResolve
. AssemblyResolve is requesting the missing DLL. Then, we will tell our application to look for the DLL in memory. Use EmbeddedAssembly.Get
to retrieve the DLL from memory and pass it for AssemblyResolve to handle the rest.
static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { string resource1 = "MyApp.System.Windows.Forms.Ribbon35.dll"; string resource2 = "MyApp.System.Data.SQLite.dll"; EmbeddedAssembly.Load(resource1, "System.Windows.Forms.Ribbon35.dll"); EmbeddedAssembly.Load(resource2, "System.Data.SQLite.dll"); AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false);S Application.Run(new Form1()); } static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { return EmbeddedAssembly.Get(args.Name); } }
Thats it.
Dive Into EmbeddedAssembly.cs
Here, we shall take a look at what is EmbeddedAssembly.cs
doing behind.
There are two common type of DLLs that will be used with .NET application
Managed DLL is fully written by .NET language (i.e. C#, VB.NET)
Unmanaged DLL will be written by other languages (i.e. C, C++)
System.Data.SQLite.DLL is Mixed Code. It is a combination of C and C#. Therefore it can be considered as Unmanaged DLL.
Procedure of Loading Managed DLL from Embedded Resource is simple.
static class Program { [STAThread] static void Main() { AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { return Load(); } }
public static Assembly Load() { byte[] ba = null; string resource = "MyApp.System.Windows.Forms.Ribbon35.dll"; Assembly curAsm = Assembly.GetExecutingAssembly(); using (Stream stm = curAsm.GetManifestResourceStream(resource)) { ba = new byte[(int)stm.Length]; stm.Read(ba, 0, (int)stm.Length); return Assembly.Load(ba); } }
Loading Unmanaged DLL
Unmanaged DLL cannot be loaded directly from stream/byte[]
as Managed DLL do.
byte[]
.byte[]
into a physical file and stored it at temp folder.Assembly.LoadFile()
to load the file into memory.
Steps are explained as comments inside codes below:
public static Assembly Load() { // Get the byte[] of the DLL byte[] ba = null; string resource = "MyApp.System.Data.SQLite.dll"; Assembly curAsm = Assembly.GetExecutingAssembly(); using (Stream stm = curAsm.GetManifestResourceStream(resource)) { ba = new byte[(int)stm.Length]; stm.Read(ba, 0, (int)stm.Length); } bool fileOk = false; string tempFile = ""; using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider()) { // Get the hash value of the Embedded DLL string fileHash = BitConverter.ToString(sha1.ComputeHash(ba)).Replace("-", string.Empty); // The full path of the DLL that will be saved tempFile = Path.GetTempPath() + "System.Data.SQLite.dll"; // Check if the DLL is already existed or not? if (File.Exists(tempFile)) { // Get the file hash value of the existed DLL byte[] bb = File.ReadAllBytes(tempFile); string fileHash2 = BitConverter.ToString(sha1.ComputeHash(bb)).Replace("-", string.Empty); // Compare the existed DLL with the Embedded DLL if (fileHash == fileHash2) { // Same file fileOk = true; } else { // Not same fileOk = false; } } else { // The DLL is not existed yet fileOk = false; } } // Create the file on disk if (!fileOk) { System.IO.File.WriteAllBytes(tempFile, ba); } // Load it into memory return Assembly.LoadFile(tempFile); }
EmbeddedAssembly.cs
will pre-load the required DLL and stored it inside a Dictionary
. When the application's Event of AssemblyResolve
is raised, EmbeddedAssembly.Get()
will return the DLL as requested.
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Reflection; using System.Security.Cryptography; public class EmbeddedAssembly { // Version 1.3 static Dictionarydic = null; public static void Load(string embeddedResource, string fileName) { if (dic == null) dic = new Dictionary (); byte[] ba = null; Assembly asm = null; Assembly curAsm = Assembly.GetExecutingAssembly(); using (Stream stm = curAsm.GetManifestResourceStream(embeddedResource)) { // Either the file is not existed or it is not mark as embedded resource if (stm == null) throw new Exception(embeddedResource + " is not found in Embedded Resources."); // Get byte[] from the file from embedded resource ba = new byte[(int)stm.Length]; stm.Read(ba, 0, (int)stm.Length); try { asm = Assembly.Load(ba); // Add the assembly/dll into dictionary dic.Add(asm.FullName, asm); return; } catch { // Purposely do nothing // Unmanaged dll or assembly cannot be loaded directly from byte[] // Let the process fall through for next part } } bool fileOk = false; string tempFile = ""; using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider()) { string fileHash = BitConverter.ToString(sha1.ComputeHash(ba)).Replace("-", string.Empty);; tempFile = Path.GetTempPath() + fileName; if (File.Exists(tempFile)) { byte[] bb = File.ReadAllBytes(tempFile); string fileHash2 = BitConverter.ToString(sha1.ComputeHash(bb)).Replace("-", string.Empty); if (fileHash == fileHash2) { fileOk = true; } else { fileOk = false; } } else { fileOk = false; } } if (!fileOk) { System.IO.File.WriteAllBytes(tempFile, ba); } asm = Assembly.LoadFile(tempFile); dic.Add(asm.FullName, asm); } public static Assembly Get(string assemblyFullName) { if (dic == null || dic.Count == 0) return null; if (dic.ContainsKey(assemblyFullName)) return dic[assemblyFullName]; return null; } }
Tip 1: Get Assembly within another assembly (Suggested by Thierry Maurel)
In case of DLLs embedded into another DLL, your can use
Assembly a1 = GetType ().Assembly;
to obtain the local dll assembly, instead of the executable one.