2015/10/26

C#.Net 將dll內嵌在exe內

這陣子寫了一些有趣的東西,又怕使用的朋友勿刪dll
所以就有了這篇文章啦XD

首先將dll複製到Project內,並將建置動作修改為「內嵌資源」及複製到輸出目錄修改為「不要複製」

將dll加入參考後將該屬性的複製到本機改為「False」,再重新建置專案即可




using System;
using System.Reflection;
using System.Windows.Forms;

namespace TestProject
{
    static class Program
    {
        /// <summary>
        /// 應用程式的主要進入點。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
            Application.Run(new Form1());
        }

        private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            //Project_Namespace.Package_Namespace.dll
            //Project Namespace = TestProject
            //Package Namesapce = Newtonsoft.Json
            using (var stream = assembly.GetManifestResourceStream("TestProject.Newtonsoft.Json.dll"))
            {
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                stream.Flush();
                stream.Close();
                return Assembly.Load(buffer);
            }
        }

    }
}



參考資料:
How to embed and access resources by using Visual C#
C# WPF, WINDOWS FORM,將DLL包進EXE執行檔,製作單一執行免安裝應用程式