1. 程式人生 > 其它 >C# 將Dll檔案打包到exe中

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