views:

193

answers:

1

I've read through the two other threads that extract the dll from the application at run time. One of these methods used the current Windows temporary directory to save the dll in, but it was an unmanaged dll and had to be imported at runtime with DllImport. Assuming that my managed dll exported to the temporary directory, how can I properly link that managed assembly to my current MSVC# project?

+2  A: 

You dont need to save to a temp directory at all. Just put the managed dll as an 'Embedded Resource' in your project. Then hook the Appdomain.AssemblyResolve event and in the event, load the resource as byte stream and load the assembly from the stream and return it.

Sample code:

// Windows Forms:
// C#: The static contructor of the 'Program' class in Program.cs
// VB.Net: 'MyApplication' class in ApplicationEvents.vb (Project Settings-->Application Tab-->View Application Events)
// WPF:
// The 'App' class in WPF applications (app.xaml.cs/vb)

static Program() // Or MyApplication or App as mentioned above
{
    AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}

static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    if (args.Name.Contains("Mydll"))
    {
        // Looking for the Mydll.dll assembly, load it from our own embedded resource
        foreach (string res in Assembly.GetExecutingAssembly().GetManifestResourceNames())
        {
            if(res.EndsWith("Mydll.dll"))
            {
                Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(res);
                byte[] buff = new byte[s.Length];
                s.Read(buff, 0, buff.Length);
                return Assembly.Load(buff);
            }
        }
    }
    return null;
} 
logicnp
Oh wow, just what I was looking for!
Gbps