一、前言
最近在搞c#
的winform
工程(.NET Framework
),需要引用一个第三方dll
,正常情况下,打包成.exe
,会自动拷贝这个dll
文件到exe
所在的目录中,能不能将.dll
嵌入到exe
中呢?答案肯定是可以滴,下面就介绍做法。
二、嵌入dll到exe的具体步骤
1、libs文件夹
在工程目录中,新建一个libs
文件夹,将你要引用的dll
放进来。
2、添加dll引用,设置不复制
添加dll
引用
打开属性窗口
在属性窗口中,对dll
设置:复制本地 False
3、设置嵌入嵌入的资源
点击libs
文件夹中的dll
,在属性窗口中设置 生成操作: 嵌入的资源
4、在代码中动态处理dll加载
在程序入口处注册AppDomain.CurrentDomain.AssemblyResolve
,处理dll
的加载。
例:
using System;
using System.Reflection;
using System.Windows.Forms;
namespace winform1
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
//注册委托
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainAssemblyResolve;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
/// <summary>
/// 加载嵌入工程中的dll
/// </summary>
private static Assembly CurrentDomainAssemblyResolve(object sender, ResolveEventArgs e)
{
//项目的命名空间为winform1, 嵌入dll资源在libs文件夹下,所以这里用的命名空间为: winform1.libs.
string dllName = "winform1.libs." + new AssemblyName(e.Name).Name + ".dll";
using (var dllStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(dllName))
{
byte[] dllData = new byte[dllStream.Length];
dllStream.Read(dllData, 0, dllData.Length);
return Assembly.Load(dllData);
}
}
}
}
三、发布exe,测试成功
发布成exe
,我们可以使用ILSpy
反编译一下exe
,可以看到dll
已经嵌入到exe
中了。
注:关于ILSpy
反编译,有兴趣的同学可以玩玩
ILSpy
下载地址:https://github.com/icsharpcode/ILSpy/releases