Csharp/C#教程:如何使用托管C#应用程序管理C#dll而不留下文件?分享


如何使用托管C#应用程序管理C#dll而不留下文件?

我已经阅读了另外两个在运行时从应用程序中提取dll的线程。 其中一种方法使用当前的Windows临时目录来保存dll,但它是一个非托管的dll,必须在运行时使用DllImport 。 假设我的托管dll导出到临时目录,我如何正确地将该托管程序集链接到我当前的MSVC#项目?

您根本不需要保存到临时目录。 只需将托管dll作为项目中的“嵌入式资源”即可。 然后挂钩Appdomain.AssemblyResolve事件,并在事件中,将资源作为字节流加载并从流中加载程序集并返回它。

示例代码:

上述就是C#学习教程:如何使用托管C#应用程序管理C#dll而不留下文件?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 // Windows Forms: // C#: The static contructor of the 'Program' class in Program.cs // VB.Net: 'MyApplication' class in ApplicationEvents.vb (Project Settings-->Application Tab-->View Application Events) // WPF: // The 'App' class in WPF applications (app.xaml.cs/vb) static Program() // Or MyApplication or App as mentioned above { AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); } static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { if (args.Name.Contains("Mydll")) { // Looking for the Mydll.dll assembly, load it from our own embedded resource foreach (string res in Assembly.GetExecutingAssembly().GetManifestResourceNames()) { if(res.EndsWith("Mydll.dll")) { Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(res); byte[] buff = new byte[s.Length]; s.Read(buff, 0, buff.Length); return Assembly.Load(buff); } } } return null; } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1023378.html

(0)
上一篇 2022年1月8日
下一篇 2022年1月8日

精彩推荐