Sometimes you want to create a portable application. A single executable that doesn't require additional library files. This article will briefly explain how to embed a DLL file as a resource so that you can have a self contained application.
Windows Forms Application
1. Go to the project properties and go to the "References" tab.
2. Click "Add..." -> "Browse" and select the DLL file you would like to use (Make note of the Reference Name).
3. While still under project properties go to the "Resources" tab.
4. Under resources select "Add Resource" -> "Add Existing File..." and select the DLL you just added add in the previous step (Make note of the Resource Name).
5. While still under project properties go to the "Application" tab and click "View Application Events"
6. Add the following import:
6a. Paste the following code into the MyApplication Class:
Private Sub AppStart(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup AddHandler AppDomain.CurrentDomain.AssemblyResolve, AddressOf ResolveAssemblies End Sub Private Function ResolveAssemblies(sender As Object, e As System.ResolveEventArgs) As Reflection.Assembly Dim desiredAssembly = New Reflection.AssemblyName(e.Name) If desiredAssembly.Name = "DLL_REFERENCE_NAME" Then 'replace DLL_REFERENCE_NAME with reference name Return Reflection.Assembly.Load(My.Resources.DLL_RESOURCE_NAME) 'replace DLL_RESOURCE_NAME with your assembly's resource name Else Return Nothing End If End Function
6b. Make sure to replace the following with the correct names.
DLL_REFERENCE_NAME = Reference Name from step 2
DLL_RESOURCE_NAME = Resource Name from step 4
In console applications you can access the application events by clicking "View Application Events". To accomplish the same thing add the following code to the top of your "Main" class.
AddHandler AppDomain.CurrentDomain.AssemblyResolve, New ResolveEventHandler(AddressOf Resolver)
Then add this function to the same module as your "Main" class.
Private Function Resolver(sender As Object, e As System.ResolveEventArgs) As Reflection.Assembly Dim desiredAssembly = New Reflection.AssemblyName(e.Name) Dim assemblyToLoad As Byte() = Nothing Select Case desiredAssembly.Name Case Is = "NetOffice" assemblyToLoad = My.Resources.NetOffice Case Is = "OfficeApi" assemblyToLoad = My.Resources.OfficeApi Case Is = "OutlookApi" assemblyToLoad = My.Resources.OutlookApi End Select If assemblyToLoad IsNot Nothing Then Return Reflection.Assembly.Load(assemblyToLoad) Else Return Nothing End If End Function