C# 將Dll文件打包到exe中
首先在資源管理里面將需要使用的dll添加進入

然后將dll文件的生成操作改成嵌入的資源


然后新建一個類 LoadResourceDll.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Text.RegularExpressions; 7 using System.Windows.Forms; 8 using System.Diagnostics; 9 using System.Reflection; 10 11 namespace LegendTool 12 { 13 public static class LoadResoureDll 14 { 15 /// <summary> 已加載DLL 16 /// </summary> 17 private static Dictionary<string, Assembly> LoadedDlls = new Dictionary<string, Assembly>(); 18 /// <summary> 已處理程序集 19 /// </summary> 20 private static Dictionary<string, object> Assemblies = new Dictionary<string, object>(); 21 /// <summary> 在對程序集解釋失敗時觸發 22 /// </summary> 23 /// <param name="sender">AppDomain</param> 24 /// <param name="args">事件參數</param> 25 private static Assembly AssemblyResolve(object sender, ResolveEventArgs args) 26 { 27 try 28 { 29 //程序集 30 Assembly ass; 31 //獲取加載失敗的程序集的全名 32 var assName = new AssemblyName(args.Name).FullName; 33 //判斷Dlls集合中是否有已加載的同名程序集 34 if (LoadedDlls.TryGetValue(assName, out ass) && ass != null) 35 { 36 LoadedDlls[assName] = null;//如果有則置空并返回 37 return ass; 38 } 39 else 40 { 41 throw new DllNotFoundException(assName);//否則拋出加載失敗的異常 42 } 43 } 44 catch (System.Exception ex) 45 { 46 return null; 47 MessageBox.Show("error:\n位置:AssemblyResolve()!\n描述:" + ex.Message); 48 } 49 } 50 51 /// <summary> 注冊資源中的dll 52 /// </summary> 53 /// <param name="pattern">*表示連續的未知字符,_表示單個未知字符,如*.dll</param> 54 public static void RegistDLL(string pattern = "*.dll") 55 { 56 System.IO.Directory.GetFiles("", ""); 57 //獲取調用者的程序集 58 var ass = new StackTrace(0).GetFrame(1).GetMethod().Module.Assembly; 59 //判斷程序集是否已經處理 60 if (Assemblies.ContainsKey(ass.FullName)) 61 { 62 return; 63 } 64 //程序集加入已處理集合 65 Assemblies.Add(ass.FullName, null); 66 //綁定程序集加載失敗事件(這里我測試了,就算重復綁也是沒關系的) 67 AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve; 68 //獲取所有資源文件文件名 69 var res = ass.GetManifestResourceNames(); 70 var regex = new Regex("^" + pattern.Replace(".", "\\.").Replace("*", ".*").Replace("_", ".") + "$", RegexOptions.IgnoreCase); 71 foreach (var r in res) 72 { 73 //如果是dll,則加載 74 if (regex.IsMatch(r)) 75 { 76 try 77 { 78 var s = ass.GetManifestResourceStream(r); 79 var bts = new byte[s.Length]; 80 s.Read(bts, 0, (int)s.Length); 81 var da = Assembly.Load(bts); 82 //判斷是否已經加載 83 if (LoadedDlls.ContainsKey(da.FullName)) 84 { 85 continue; 86 } 87 LoadedDlls[da.FullName] = da; 88 } 89 catch (Exception ex) 90 { 91 MessageBox.Show("error:加載dll失敗\n位置:RegistDLL()!\n描述:" + ex.Message); 92 } 93 } 94 } 95 } 96 } 97 }
在程序入庫添加引用
LoadResoureDll.RegistDLL();

參考原文:https://blog.csdn.net/yanhuatangtang/article/details/76228155

浙公網安備 33010602011771號