zoukankan      html  css  js  c++  java
  • 通过AssemblyResolve事件打包合并exe和dll文件

     使用WPF开发的安装包,在创建快捷方式的时候,需要用到COM程序集Windows Script Host Object Model,引用COM程序集后,会在debug目录生成Interop.IWshRuntimeLibrary.dll,但是运行的时候,需要把这个dll放到exe一起,否则会报“未能加载文件或程序集...”的错误。

    网上搜索了一番,说是可以通过ILmerge工具解决,具体步骤如下:

    步骤一:下载并安装”ILMerge“,下载链接:https://www.microsoft.com/en-us/download/details.aspx?id=17630 

    步骤二:安装完成以后,将exe文件和dll文件拷贝到ILMerge目录下,打开CMD,进入到ILMerge目录,执行命令

    ilmerge /targetplatform:v2 /ndebug  /target:winexe /out:setup2.exe /log:log.txt  setup.exe Interop.IWshRuntimeLibrary.dll

    源程序setup.exe是.net 3.5,但是这个工具的/targetplatform只能选 v1 v2 v4,试了v2 和v4,生成都能生成成功,但是生成的setup2.exe都无法运行,放弃。。。

    方法二用到AssemblyResolve事件,该事件在对程序集的解析失败时发生,具体可以看msdn上的解释:https://msdn.microsoft.com/zh-cn/library/system.appdomain.assemblyresolve.aspx

    步骤一:将Interop.IWshRuntimeLibrary.dll作为资源添加到exe项目

    步骤二:在APP构造函数中注册AssemblyResolve事件,在AssemblyResolve事件中加载该资源,具体代码如下

            public App()
            {
                AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
            }
            private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
            {
                Properties.Resources res = new Properties.Resources();
                PropertyInfo dotnetpinfo = res.GetType().GetProperties(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Instance).Where(t => t.Name == "Interop_IWshRuntimeLibrary").FirstOrDefault();
                byte[] bytes = (byte[])dotnetpinfo.GetValue(res, null);
                return System.Reflection.Assembly.Load(bytes);
            }            

    上面的代码还可改进一下,判断args参数,如果是缺少Interop_IWshRuntimeLibrary时才从资源里加载,否则抛出异常

  • 相关阅读:
    C# 不用添加WebService引用,调用WebService方法
    贪心 & 动态规划
    trie树 讲解 (转载)
    poj 2151 Check the difficulty of problems (检查问题的难度)
    poj 2513 Colored Sticks 彩色棒
    poj1442 Black Box 栈和优先队列
    啦啦啦
    poj 1265 Area(pick定理)
    poj 2418 Hardwood Species (trie树)
    poj 1836 Alignment 排队
  • 原文地址:https://www.cnblogs.com/xienb/p/9305369.html
Copyright © 2011-2022 走看看