• [织梦吧]唯一域名:www.dedecms8.com,织梦DedeCMS学习平台.

当前位置: > 编程与数据库 > net编程 >

嵌入Dll到.net程序中的方法

来源: www.dedecms8.com 编辑:织梦吧 时间:2012-06-27点击:

 我们经常会写一些小程序给自己或者他人用,而这些程序时长又会去引用一些第三方的Dll,比如开源的 ICSharpCode.SharpZipLib.dll等,为了让程序保持整洁,或者给对方的时候方便,就想把这些dll给嵌入到EXE中去,这样在不打包的情况下,只要丢一个文件给对方就能用了.最近研究了下可行性,目前有如下两种方法:

方法1:把相关的第三方dll作为程序资源嵌入到EXE中,在程序运行的时候,从资源文件中输出到程序执行目录即可

(图1:示例项目,ThirdPartydlldemo.dll作为第三方资源.Build Action属性设置为" Embedded Resource")

然后在Program.cs里面声明个静态构造函数,在该方法里面把第三方dll输出到程序目录,这样在调用第三方dll方法的时候,相关环境已经初始化完毕了.

1: private static void ExtractResourceToFile(string resourceName, string filename)
2:  {
3:     if (!System.IO.File.Exists(filename))
4:       using (System.IO.Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
5:       usng (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create))
6:       {
7:          byte[] b = new byte[s.Length];
8:          s.Read(b, 0, b.Length);
9:          fs.Write(b, 0, b.Length);
10:       }
11:   }

1: static Program()
2:    {
3:      ExtractResourceToFile("EmbeddedDLL2ExeDemo.ThirdPartyDllDemo.dll",
4:        "ThirdPartyDllDemo.dll");
5:    }

这样就ok了.

方法2:是用Ilmerge这个微软提供的工具,直接把相关的dll嵌入到目标exe中,而且程序运行时候,不像方法1会把相关的dll输出到可执行目录下,它直接让.net运行时到程序的资源中去找相关的dll引用,以下是Ilmerge的介绍:

This document describes the ILMerge utility which merges multiple .NET assemblies into a single assembly. However, some .NET assemblies may not be able to be merged because they may contain features such as unmanaged code. I would highly recommend using peverify (the .NET Framework SDK tool) on the output of ILMerge to guarantee that the output is verifiable and will load in the .NET runtime.

ILMerge is packaged as a console application. But all of its functionality is also accessible programmatically. Note that Visual Studio does allow one to add an executable as a reference, so you can write a client that uses ILMerge as a library.

About D8

  • ©2014 织梦吧(d8) DedeCMS学习交流平台
  • 唯一网址 www.DedeCMS8.com 网站地图
  • 联系我们 1170734538@qq.com ,  QQ