NX二次开发中,C#实现dll启动时释放dlx文件
1.在做一些小功能时,或者发送一些功能给其他人使用时,
做过开发的都知道,只是要发一个dll跟一个dlx,这是最基本的,有些需要读取数据的功能,还可能需要用到一些表格,
因此参考了网上部分教程来做了这个实现,
*功能效果:仅有一个dll文件即可执行程序
*功能思路:嵌入资源到dll内,使用时,释放它,结束时,删除它!
语言:C# .net4.8
方法如下
1.实现方法 ,网上找的
/// <summary>
/// 释放内嵌资源至指定位置
/// </summary>
/// <param name="resource">嵌入的资源,此参数写作:命名空间.文件夹名.文件名.扩展名</param>
/// <param name="path">释放到位置</param>
private void ExtractFile(String resource, String path)
{
Assembly assembly = Assembly.GetExecutingAssembly();
BufferedStream input = new BufferedStream(assembly.GetManifestResourceStream(resource));
FileStream output = new FileStream(path, FileMode.Create);
byte[] data = new byte[1024];
int lengthEachRead;
while ((lengthEachRead = input.Read(data, 0, data.Length)) > 0)
{
output.Write(data, 0, lengthEachRead);
}
output.Flush();
output.Close();
}
2.在构造函数内声明dlx在整个项目内的地址
public Dll_and_Dlx()
{
try
{
theSession = Session.GetSession();
theUI = UI.GetUI();
string temp = "Dll_and_Dlxs.Resources.Dll_and_Dlx.dlx";
//在这里使用ExtractFile()方法
ExtractFile(temp, Arong_Nx.Arong_Nx_App.GetPath("Dll_and_Dlx.dlx"));
theDialog = theUI.CreateDialog(Arong_Nx.Arong_Nx_App.GetPath("Dll_and_Dlx.dlx"));
theDialog.AddApplyHandler(new NXOpen.BlockStyler.BlockDialog.Apply(apply_cb));
theDialog.AddOkHandler(new NXOpen.BlockStyler.BlockDialog.Ok(ok_cb));
theDialog.AddUpdateHandler(new NXOpen.BlockStyler.BlockDialog.Update(update_cb));
theDialog.AddInitializeHandler(new NXOpen.BlockStyler.BlockDialog.Initialize(initialize_cb));
theDialog.AddDialogShownHandler(new NXOpen.BlockStyler.BlockDialog.DialogShown(dialogShown_cb));
}
catch (Exception ex)
{
//---- Enter your exception handling code here -----
throw ex;
}
}
3.将dlx文件设置为嵌入的资源
记得修饰符要改为Public,否则GetManifestResourceStream()方法会返回null !
4.结束时 删除它,传递这个dlx的路径即可
public static void UnloadLibrary(string arg)
{
try
{
File.Delete(Arong_Nx.Arong_Nx_App.GetPath("Dll_and_Dlx.dlx"));
}
catch (Exception ex)
{
//---- Enter your exception handling code here -----
theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString());
}
}
5.这个是获得dlx路径的方法(自己写的方法)
/// <summary>
/// 返回dll的路径
/// </summary>
/// <returns></returns>
static public string GetPath(string dlx)
{
return AppDomain.CurrentDomain.BaseDirectory + dlx;
}
6.调试如下
项目地址
Github内搜索 Dll_and_Dlx