【问题标题】:Embed all DLLs in win app and C#将所有 DLL 嵌入 win 应用程序和 C#
【发布时间】:2012-08-26 21:34:45
【问题描述】:

我使用此代码将所有 dll 嵌入到应用程序 exe 文件中,但此代码只能嵌入一个 dll。我搜索其他代码,但都是一样的。

public App()
{
    AppDomain.CurrentDomain.AssemblyResolve +=new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}

System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll","");

    dllName = dllName.Replace(".", "_");

    if (dllName.EndsWith("_resources")) return null;

    System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());

    byte[] bytes = (byte[])rm.GetObject(dllName);

    return System.Reflection.Assembly.Load(bytes);
}

要使用 ILmerge,我的 dll 有问题。所以我不能用这个。 我怎样才能做到这一点?

【问题讨论】:

  • 我使用第三方程序集,希望用户无法理解这一点。
  • 你已经成功了,我看不懂。如果 ILMerge 失败,则 Assembly.Load(byte[]) 很可能也会失败。它无法加载包含本机代码的 DLL。将您的可执行文件打包到一个名为 setup.exe 的文件中,然后使用安装项目创建一个。

标签: c# dll embed exe


【解决方案1】:

这个开源工具应该可以帮助你

http://madebits.com/netz/

【讨论】:

    【解决方案2】:

    一种可能的方法是将所有 DLL 添加到资源中(手动)。然后,在程序启动时,使用File.WriteAllBytes 将这些资源字节流写入文件。

    注意:在这种情况下,您不能使用DllImport,因为它需要常量字符串路径。相反,您将使用所谓的“动态 P\Invoke”。 Learn more.

    【讨论】:

      【解决方案3】:

      使用 GetManifestResourceStream 应该会更好。

      当 dll 作为资源嵌入时,资源名称以您项目的默认名称空间为前缀,因此您需要填写。

      例如

      static  System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
      {
          string defaultNameSpace = "...";
      
          string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll", "");
      
          string resourceName = String.Format("{0}.{1}.dll", defaultNameSpace , dllName);
      
          using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
          {
               if (stream == null)  
                   return null;
      
               byte[] data = new byte[stream.Length];
               stream.Read(data, 0, data.Length);
               return Assembly.Load(data);
           }
       }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-16
        • 1970-01-01
        • 1970-01-01
        • 2012-05-10
        • 2012-01-02
        • 2011-11-22
        • 1970-01-01
        相关资源
        最近更新 更多