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

走远了吗. 提交于 2019-12-04 02:38:56

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/2452114/how-do-package-managed-c-sharp-dlls-with-a-managed-c-sharp-application-without-l

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!