C#將DLL嵌入到exe當中

我就直接上內容了。雖然能看懂,知道原理。但是自己還是無法獨立寫出來。看來還需要多學習啊。。


原文地址,程序我自己重新做了一遍


首先,你需要一個解決方案,並且包含已經引用的第三方的dll

wKioL1Z9AQDxGno8AACbzPrnnmM730.png


2.打開Properties下的Resources,將需要包含的dll添加進去

wKiom1Z9ATrQdUPxAAB8LHj81SM256.png

wKioL1Z9ApGw4zr1AAA2qopdAMc585.png

wKiom1Z9ATrBi8UTAABxEU6DI4A093.png


3.在Form1.cs中添加代碼

  public Form1() {
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
            InitializeComponent();
}
 private System.Reflection.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", System.Reflection.Assembly.GetExecutingAssembly());
            byte[] bytes = (byte[])rm.GetObject(dllName);
            return System.Reflection.Assembly.Load(bytes);
 }


4.重新生成解決方案即可,然後你可以在bin文件夾中找到已經嵌入dll的exe


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章