开发者

How do package managed C# dlls with a managed C# application without leaving behind files?

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 temporar开发者_运维技巧y directory, how can I properly link that managed assembly to my current MSVC# project?


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;
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜