在使用WPF寫(xiě)一些小工具時(shí),往往需要將多個(gè)DLL文件嵌入到EXE文件里,生成單文件。這里介紹三種方案:
- 把DLL文件作為嵌入資源
- 使用Costura.Fody
- 使用.NET Reactor。
一、把DLL文件轉(zhuǎn)換為嵌入資源
第一步,在項(xiàng)目中新建Resources文件夾,把需要的dll文件拷貝到該目錄中(可以是多個(gè)dll文件),然后修改每個(gè)文件的屬性,將生成操作改為嵌入的資源,例如:


第二步,修改
App.xaml.cs文件,添加程序集解析失敗事件,并加載指定的嵌入資源。修改后內(nèi)容為:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
namespace Embed
{
/// <summary>
/// App.xaml 的交互邏輯
/// </summary>
public partial class App : Application
{
readonly string[] dlls = new string[] { "Newtonsoft.Json" }; // 去掉后綴名
public App()
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}
private System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string resources = null;
foreach (var item in dlls)
{
if (args.Name.StartsWith(item))
{
resources = item + ".dll";
break;
}
}
if (string.IsNullOrEmpty(resources)) return null;
var assembly = Assembly.GetExecutingAssembly();
resources = assembly.GetManifestResourceNames().FirstOrDefault(s => s.EndsWith(resources));
if (string.IsNullOrEmpty(resources)) return null;
using (Stream stream = assembly.GetManifestResourceStream(resources))
{
if (stream == null) return null;
var block = new byte[stream.Length];
stream.Read(block, 0, block.Length);
return Assembly.Load(block);
}
}
}
}
其中dlls數(shù)組內(nèi)容為Resources目錄下去掉后綴的文件名。比如Resources目錄下有Newtonsoft.Json.dll、MaterialDesignThemes.Wpf.dll和MaterialDesignColors.dll,則dlls數(shù)組內(nèi)容為
readonly string[] dlls = new string[] { "Newtonsoft.Json" , "MaterialDesignThemes.Wpf" , "MaterialDesignColors"};
最后重新生成項(xiàng)目,刪除生成目錄下的dll文件即可。
二、使用Costura.Fody
Costura.Fody可以把引用的庫(kù)文件嵌入為資源,使用起來(lái)非常簡(jiǎn)單,直接安裝Costura.Fody即可:
PM> Install-Package Costura.Fody
舉一個(gè)簡(jiǎn)單例子:
- 新建一個(gè)WPF項(xiàng)目,添加Newtonsoft.Json:
PM> Install-Package Newtonsoft.Json - 安裝Costura.Fody
- 生成項(xiàng)目
生成結(jié)果如下:

三、使用 .NET Reactor
.NET Reactor是一款.NET代碼加密混淆工具,同時(shí)具有掃描依賴,并嵌入程序集的功能。
具體使用步驟:
- 打開(kāi)WPF項(xiàng)目生成的exe文件
- 點(diǎn)擊掃描依賴項(xiàng)按鈕;
- 勾選嵌入所有程序集;
- 點(diǎn)擊保護(hù)即可。
生成結(jié)果如下:使用流程生成結(jié)果
總的來(lái)說(shuō),上面三種方式都可以嵌入dll資源,生成單文件。Costura.Fody和.NET Reactor使用起來(lái)方便,改動(dòng)最小。如果還有加密需求,那就推薦使用.NET Reactor。
版權(quán)聲明:本文為「txfly」的原創(chuàng)文章,遵循 CC 4.0 BY-SA 版權(quán)協(xié)議,轉(zhuǎn)載請(qǐng)附上原文出處鏈接及本聲明。
原文鏈接:http://www.itdecent.cn/p/72534a7e2f4a

