新发的日常小实验——c#的.net工程(winform桌面窗体应用)如何将引用的dll嵌入到exe中

it2023-08-16  78

文章目录

一、前言二、嵌入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放进来。

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

最新回复(0)