软件编程
位置:首页>> 软件编程>> C#编程>> C# 嵌入dll 的方法

C# 嵌入dll 的方法

作者:树荫下的阳光  发布时间:2022-11-06 08:39:10 

标签:C#,嵌入,dll

在很多时候我们在生成C#exe文件时,如果在工程里调用了dll文件时,那么如果不加以处理的话在生成的exe文件运行时需要连同这个dll一起转移,相比于一个单独干净的exe,这种形式总归让人不爽,那么有办法让生成的软件中直接就包含这个dll文件吗,这样就可以不用dll跟着exe走了,避免单独不能运行的情况。

        答案是有的!  

C# 嵌入dll 的方法

      在工程项目目录下找到Resources.resx文件并点击,然后按下面操作,添加资源,将你要加入的dll添加进来。       

C# 嵌入dll 的方法

      操作完成后,就会在下面的内容框里看到你添加进来的dll。    

C# 嵌入dll 的方法

        然后在工程中加入下面这个函数代码:


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);
   }

在InitializeComponent();之前调用。这样生成的exe就包含这个dll文件啦。


public Form1()
   {
     this.StartPosition = FormStartPosition.CenterScreen;
     AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
     InitializeComponent();
   }

总结

以上所述是小编给大家介绍的C# 嵌入dll 的方法,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

来源:https://www.cnblogs.com/wangshucai/archive/2018/07/07/9277822.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com