Lars Holm Jensen's Code Blog

Just another WordPress codeblog on C#, Silverlight and all things .NET

Archive for the ‘dll’ tag

Embed managed dlls easily in a .NET assembly

with 31 comments

Here’s a very quick and dirty way to include managed dlls in your .exe-file. Just right-click your project in Visual Studio, choose Project Properties -> Resources -> Add Resource -> Add Existing File

Add all your dependencies and finally include the code below in your App.xaml.cs or equivalent.. everything else is taken care of.

public App()
    AppDomain.CurrentDomain.AssemblyResolve +=new ResolveEventHandler(CurrentDomain_AssemblyResolve);

System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
    string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll","");

    dllName = dllName.Replace(".", "_");

    if (dllName.EndsWith("_resources")) return null;

    System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());

    byte[] bytes = (byte[])rm.GetObject(dllName);

    return System.Reflection.Assembly.Load(bytes);

The code is a little bit more complicated than need be. But I wanted to avoid using a named namespace in order to keep the code copy-paste-ready. By the way LINQPad uses a similar method, though Joe Albahari has gone a step further and encrypted his resources.

Written by larsholm

June 15th, 2011 at 8:10 pm

Posted in .NET

Tagged with , , , , , ,