Created
November 4, 2015 20:57
-
-
Save wojciech-kulik/4f444b6acdb0320d4973 to your computer and use it in GitHub Desktop.
[C#] Load DLLs from resources - http://wojciechkulik.pl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Reflection; | |
using System.Windows.Forms; | |
namespace EmbeddedLibraries | |
{ | |
static class Program | |
{ | |
private static Assembly ExecutingAssembly = Assembly.GetExecutingAssembly(); | |
private static string[] EmbeddedLibraries = | |
ExecutingAssembly.GetManifestResourceNames().Where(x => x.EndsWith(".dll")).ToArray(); | |
[STAThread] | |
static void Main() | |
{ | |
// Attach custom event handler | |
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; | |
Application.EnableVisualStyles(); | |
Application.SetCompatibleTextRenderingDefault(false); | |
Application.Run(new Form1()); | |
} | |
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) | |
{ | |
// Get assembly name | |
var assemblyName = new AssemblyName(args.Name).Name + ".dll"; | |
// Get resource name | |
var resourceName = EmbeddedLibraries.FirstOrDefault(x => x.EndsWith(assemblyName)); | |
if (resourceName == null) | |
{ | |
return null; | |
} | |
// Load assembly from resource | |
using (var stream = ExecutingAssembly.GetManifestResourceStream(resourceName)) | |
{ | |
var bytes = new byte[stream.Length]; | |
stream.Read(bytes, 0, bytes.Length); | |
return Assembly.Load(bytes); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment