溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

c#項(xiàng)目將dll打包到exe中的步驟是什么

發(fā)布時(shí)間:2021-04-06 10:14:00 來源:億速云 閱讀:215 作者:小新 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)c#項(xiàng)目將dll打包到exe中的步驟是什么,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

意圖:

想將項(xiàng)目用到的兩個(gè)dll庫文件(CryptEnDe.dll和ICSharpCode.SharpZipLib.dll)一同編譯進(jìn)exe中,并編譯后僅一個(gè)exe程序就可以獨(dú)立運(yùn)行不再需要其它文件。

實(shí)現(xiàn):

1、將兩個(gè)dll庫文件作為資源文件添加進(jìn)項(xiàng)目中;

2、添加功能代碼

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.IO;
 
 
namespace AutoUpdateServer.Core
{
  /// <summary> 載入資源中的動(dòng)態(tài)鏈接庫(dll)文件
  /// </summary>
  static class LoadResourceDll
  {
    static Dictionary<string, Assembly> Dlls = new Dictionary<string, Assembly>();
    static Dictionary<string, object> Assemblies = new Dictionary<string, object>();
 
 
    static Assembly AssemblyResolve(object sender, ResolveEventArgs args)
    {
      //程序集
      Assembly ass;
      //獲取加載失敗的程序集的全名
      var assName = new AssemblyName(args.Name).FullName;
      //判斷Dlls集合中是否有已加載的同名程序集
      if (Dlls.TryGetValue(assName, out ass) && ass != null)
      {
        Dlls[assName] = null;//如果有則置空并返回
        return ass;
      }
      else
      {
        throw new DllNotFoundException(assName);//否則拋出加載失敗的異常
      }
    }
 
 
    /// <summary> 注冊(cè)資源中的dll
    /// </summary>
    public static void RegistDLL()
    {
      //獲取調(diào)用者的程序集
      var ass = new StackTrace(0).GetFrame(1).GetMethod().Module.Assembly;
      //判斷程序集是否已經(jīng)處理
      if (Assemblies.ContainsKey(ass.FullName))
      {
        return;
      }
      //程序集加入已處理集合
      Assemblies.Add(ass.FullName, null);
      //綁定程序集加載失敗事件(這里我測(cè)試了,就算重復(fù)綁也是沒關(guān)系的)
      AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve;
      //獲取所有資源文件文件名
      var res = ass.GetManifestResourceNames();
      foreach (var r in res)
      {
        //如果是dll,則加載
        if (r.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
        {
          try
          {
            if (r.Contains("CryptEnDe.dll") 
              || r.Contains("CryptEnDe_d.dll"))
            {
              ExtractResourceToFile(r, PathUtils.GetUpdateDllPath() + @"/" + r.Substring(r.IndexOf('.') + 1));
            }
 
 
            var s = ass.GetManifestResourceStream(r);
            var bts = new byte[s.Length];
            s.Read(bts, 0, (int)s.Length);
            var da = Assembly.Load(bts);
            //判斷是否已經(jīng)加載
            if (Dlls.ContainsKey(da.FullName))
            {
              continue;
            }
            Dlls[da.FullName] = da;
          }
          catch(Exception e)
          {
            //加載失敗就算了...
          }
        }
      }
    }
 
 
    private static void ExtractResourceToFile(string resourceName, string filename)
    {
      //if (!System.IO.File.Exists(filename))
      {
        using (System.IO.Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
        {
          using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
          {
            byte[] b = new byte[s.Length];
            s.Read(b, 0, b.Length);
            fs.Write(b, 0, b.Length);
          }
        }
      }
    }
 
 
  }
}

其中PathUtils.GetUpdateDllPath()函數(shù)為獲取dll釋放的路徑,根據(jù)自己需要指定路徑

public static string GetUpdateDllPath()
{
  string strPath = @"C:/LTShiyi/cache/updatedll";
  if (!Directory.Exists(strPath))
  {
    Directory.CreateDirectory(strPath);
  }
 
   return strPath;
}

3、在程序入口Program類中調(diào)用上面的接口函數(shù)

static Program()
{
  AutoUpdateServer.Core.LoadResourceDll.RegistDLL();
}

4、編譯即可。

關(guān)于“c#項(xiàng)目將dll打包到exe中的步驟是什么”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI