C# 非托管dll及文件嵌入exe方法
推荐使用方法二,因为方法一会在程序根目录下释放出嵌入的文件,方法二则不会。
方法一
- 解决方案资源管理器中,双击打开Properties文件夹下的Resources.resx,点击添加资源-添加现有文件
- 选择要添加的文件,如dll和xsd文件
- 点击添加的文件,查看文件属性
- 在程序中按文件属性加载文件数据,并在exe运行时释放对应文件
namespace paint
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
Unzip();
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
//释放函数
static void Unzip()
{
byte[] byDll = global::paint.Properties.Resources.OpenNR_IF;//获取嵌入dll文件的字节数组
string strPath = Application.StartupPath + @"\OpenNR-IF.dll";//设置释放路径
//创建dll文件(覆盖模式)
using (FileStream fs = new FileStream(strPath, FileMode.Create))
{
fs.Write(byDll, 0, byDll.Length);
}
string byXML = global::paint.Properties.Resources.UserApp_protocol_verification;//获取嵌入xsd文件
strPath = Application.StartupPath + @"\UserApp_protocol_verification.xsd";//设置释放路径
//创建txt文本
System.IO.File.WriteAllText(@strPath, byXML);
}
}
}
方法二
- 右键引用,选择“管理NuGet程序包”,搜索 “fody”,安装Costura.Fody。
- 在根目录创建创建文件夹: Costura64,如果是32位改为Costura32
- 把需要嵌入的文件复制到该文件夹中,在生成时,会自动寻找 Costura64和Costura32文件夹中的文件
- Costura64文件夹内的文件设置为“嵌入的资源”