C# 嵌入dll

时间:2022-03-19 19:07:18

  在很多时候我们在生成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(, 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();
}