【问题标题】:How do package managed C# dlls with a managed C# application without leaving behind files?如何在不留下文件的情况下将托管 C# dll 与托管 C# 应用程序打包在一起?
【发布时间】:2010-03-16 04:28:17
【问题描述】:

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

【问题讨论】:

    标签: c# embedded-resource managed


    【解决方案1】:

    您根本不需要保存到临时目录。只需将托管 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;
    } 
    

    【讨论】:

      猜你喜欢
      • 2014-12-01
      • 2012-02-13
      • 1970-01-01
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      • 2020-01-25
      • 2012-02-29
      • 1970-01-01
      相关资源
      最近更新 更多