Winform 将dll库打包到exe文件中并动态加载

使用Winform编写的exe文件,如果有引用到外部dll文件(如 Newtonsoft.Json.dll),使用时通常需要将dll文件拷贝到exe同目录来才能使用。

但是,如果我们将dll文件作为资源引入到winform项目中,就可以使dll文件自动被打包到exe文件内。然后,在程序运行时,将资源中包含的dll文件字节码解析出来然后加载,就可以做到整个程序只有一个exe文件了。这个技巧会在编写一些小工具的时候,让工程变得清爽很多。

下面是解析dll资源字节码的代码实现:

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);
}

然后,在程序开始的地方绑定调用:

AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 using1174@foxmail.com

文章标题: Winform 将dll库打包到exe文件中并动态加载

文章字数: 250

本文作者: Jun

发布时间: 2018-06-29, 16:17:00

最后更新: 2018-06-29, 16:36:15

原始链接: http://yoursite.com/2018/06/29/Winform-将dll库打包到exe文件中并动态加载/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏