c#将dll嵌入exe文件
在c#开发过程中,发现小项目采用setup的方式安装确实有些麻烦,于是在搜集资料的情况下,加上亲自试验,特此决定记录一番。
采用的工具是vs2019,c#开发环境。
(注:framework至少在 4.0以上)
发现问题:c#生成的调用依赖库的文件会生成dll文件,只将exe文件复制到其他路径则无法单独使用。
解决过程:
- 生成文件(debug或release)
- 在项目文件夹/bin/debug 或者release目录下找到依赖的dll文件
- 双击Resources.resx
- 选择添加资源----添加现有文件
- 将dll文件导入
- 不需要把dll文件设置成“嵌入的资源”
- 进入Form1.cs
- 看下面代码
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);
}
public Form1()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
InitializeComponent();
}
在这里就算完成了,将exe文件复制到其他路径试试看效果吧!
参考: