C# 嵌入dll

  在不少時候咱們在生成C#exe文件時,若是在工程裏調用了dll文件時,那麼若是不加以處理的話在生成的exe文件運行時須要連同這個dll一塊兒轉移,相比於一個單獨乾淨的exe,這種形式總歸讓人不爽,那麼有辦法讓生成的軟件中直接就包含這個dll文件嗎,這樣就能夠不用dll跟着exe走了,避免單獨不能運行的狀況。函數

        答案是有的!this

        

      在工程項目目錄下找到Resources.resx文件並點擊,而後按下面操做,添加資源,將你要加入的dll添加進來。spa

          

      操做完成後,就會在下面的內容框裏看到你添加進來的dll。code

        

        而後在工程中加入下面這個函數代碼:orm

1    System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
2         {
3             string dllName = args.Name.Contains(",") ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll", "");
4             dllName = dllName.Replace(".", "_");
5             if (dllName.EndsWith("_resources")) return null;
6             System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());
7             byte[] bytes = (byte[])rm.GetObject(dllName);
8             return System.Reflection.Assembly.Load(bytes);
9         }

在InitializeComponent();以前調用。這樣生成的exe就包含這個dll文件啦。blog

1   public Form1()
2         {
3             this.StartPosition = FormStartPosition.CenterScreen;
4             AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
5             InitializeComponent();
6         }
相關文章
相關標籤/搜索