- 一、前言
- 二、嵌入dll到exe的具体步骤
- 1、libs文件夹
- 2、添加dll引用,设置不复制
- 3、设置嵌入嵌入的资源
- 4、在代码中动态处理dll加载
- 三、发布exe,测试成功
最近在搞c#的winform工程(.NET Framework),需要引用一个第三方dll,正常情况下,打包成.exe,会自动拷贝这个dll文件到exe所在的目录中,能不能将.dll嵌入到exe中呢?答案肯定是可以滴,下面就介绍做法。
二、嵌入dll到exe的具体步骤 1、libs文件夹在工程目录中,新建一个libs文件夹,将你要引用的dll放进来。
添加dll引用
打开属性窗口
在属性窗口中,对dll设置:复制本地 False
点击libs文件夹中的dll,在属性窗口中设置 生成操作: 嵌入的资源
在程序入口处注册AppDomain.CurrentDomain.AssemblyResolve,处理dll的加载。
例:
using System;
using System.Reflection;
using System.Windows.Forms;
namespace winform1
{
static class Program
{
///
/// 应用程序的主入口点。
///
[STAThread]
static void Main()
{
//注册委托
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainAssemblyResolve;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
///
/// 加载嵌入工程中的dll
///
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



