Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including a DLL as an Embedded Resource in a WPF project

I'm following http://blogs.msdn.com/b/microsoft_press/archive/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition.aspx

I've added WPFToolkit.Extended.dll to my solution, and set its Build Action to Embedded Resource.

In App.OnStartup(StartupEventArgs e) I have the following code:

AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
    String resourceName = "AssemblyLoadingAndReflection." + new AssemblyName(args.Name).Name + ".dll";
    String assemblyName = Assembly.GetExecutingAssembly().FullName;
    Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
    using (stream)
    {
        Byte[] assemblyData = new Byte[stream.Length];
        stream.Read(assemblyData, 0, assemblyData.Length);
        return Assembly.Load(assemblyData);
    }
};

The debugger hits this block of code twice.

First time:

resourceName is "AssemblyLoadingAndReflection.StatusUtil.resources.dll"
assemblyName is "StatusUtil, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
stream is null

Second time:

resourceName is "AssemblyLoadingAndReflection.WPFToolkit.Extended.resources.dll"
assemblyName is "StatusUtil, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
stream is null

The code throws an exception when it hits stream.Length, since it's null.

I can't use ILMerge because it's a WPF project.

like image 658
epalm Avatar asked Jun 23 '11 17:06

epalm


Video Answer


1 Answers

You have to change the string "AssemblyLoadingAndReflection" to the name of your application assembly.

One thing you can do to make this code more generic by using some more reflection:

Assembly.GetExecutingAssembly().FullName.Split(',').First()

Don't forget to append a dot. This will of course not work if the dll is not in the resources of the application assembly.

like image 184
H.B. Avatar answered Nov 04 '22 18:11

H.B.