C# 嵌入资源实现 exe 文件内嵌 dll
- 内嵌资源
- 加载 dll 以使程序正常运行
内嵌资源
这里以 Newtonsoft_Json
为例
这只是第一步
完成这一步之后 dll 就会嵌入到 exe 文件中,但是此时程序是找不到所需的dll 的
加载 dll 以使程序正常运行
在程序的构造函数中引入
实现代码
/// <summary>
/// 加载任意位置的程序集
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
/// <returns></returns>
private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string dllName = args.Name.Contains(",") ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll", "");
dllName = dllName.Replace(".", "_");
if (dllName.EndsWith("_resources")) return null;
System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + ".Properties.Resources", Assembly.GetExecutingAssembly());
byte[] bytes = (byte[])rm.GetObject(dllName);
return Assembly.Load(bytes);
}
内嵌 dll 的方式有多种,选这种方式是因为其比较灵活