先下載最新的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執行完命令後的內容輸出。可以根據輸出的信息來判斷是否執行成功
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); }