如何使用托管C#应用程序管理C#dll而不留下文件?

时间:2010-03-16 04:28:17

标签: c# embedded-resource managed

我已经阅读了另外两个在运行时从应用程序中提取dll的线程。其中一种方法使用当前的Windows临时目录来保存dll,但它是一个非托管的dll,必须在运行时使用DllImport导入。假设我的托管dll导出到临时目录,我如何正确地将该托管程序集链接到我当前的MSVC#项目?

1 个答案:

答案 0 :(得分:3)

根本不需要保存到临时目录。只需将托管dll作为项目中的“嵌入式资源”。然后挂钩Appdomain.AssemblyResolve事件,并在事件中,将资源作为字节流加载并从流中加载程序集并返回它。

示例代码:

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