使用ILMerge将应用程序合并成一个exe

先下载最新的ILMerge工具,是一个exe文件,另外最新的工具需要和System.Compiler.dll放在一个目录下。这样在调用ILMerge.exe的时候,就不会报错了

然后通过调用cmd.exe 来辅助生成一个exe

                Process p = new Process();
                //设置要启动的应用程序
                p.StartInfo.FileName = "cmd.exe";
                //是否使用操作系统shell启动
                p.StartInfo.UseShellExecute = false;
                // 接受来自调用程序的输入信息
                p.StartInfo.RedirectStandardInput = true;
                //输出信息
                p.StartInfo.RedirectStandardOutput = true;
                // 输出错误
                p.StartInfo.RedirectStandardError = true;
                //不显示程序窗口
                p.StartInfo.CreateNoWindow = true;
                //启动程序
                p.Start();
                p.StandardInput.AutoFlush = true;

                //向cmd窗口发送输入信息
                var invokePath = System.IO.Path.Combine(appStartupPath + "\\Pack\\",  $"{projectAssembleName}.exe");
                var exePath = appStartupPath + "\\Invoker\\";
                ilmergePath = appStartupPath + "\\ILMerge\\";
               
                string cmdline = $@"""{ilmergePath}ilmerge.exe"" /ndebug /target:exe /out:{invokePath} /log {exePath}main.exe /log {dllPath} /log {exePath}Newtonsoft.Json.dll /log {exePath}ICSharpCode.SharpZipLib.dll /targetplatform:v4";
                p.StandardInput.WriteLine(cmdline + "&exit");
                string output = p.StandardOutput.ReadToEnd();
                //等待程序执行完退出进程
                p.WaitForExit();
                p.Close();

我们可以将ILMerge.exe和System.Compiler.dll放在程序的某个目录下,这样可以直接从这个目录下调用,譬如""{ilmergePath}ilmerge.exe"",要用到双引号括起来,表示

string output = p.StandardOutput.ReadToEnd();  表示cmd执行完命令后的内容输出。可以根据输出的信息来判断是否执行成功 &exit要记得加上,否则会一直等待
 if (output.Contains("ILMerge: Done."))
                {
                    if(File.Exists(System.IO.Path.Combine(appStartupPath + "\\Pack\\", invokename + ".exe")))
                    {
                        File.Delete(System.IO.Path.Combine(appStartupPath + "\\Pack\\", invokename + ".exe"));
                    }
                    File.Move(invokePath, System.IO.Path.Combine(appStartupPath + "\\Pack\\", invokename + ".exe"));
                    MessageBox.Show("打包成功");
                }
                else
                {
                    MessageBox.Show("打包异常!\n" + output);
                }

 

 
posted @ 2022-02-24 16:42  一条大河啊波浪宽啊  阅读(386)  评论(0编辑  收藏  举报