[login] ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.NetworkInformation; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using static System.Windows.Forms.VisualStyles.VisualStyleElement; namespace AutoUp { public partial class Form1 : Form { private System.Windows.Forms.Timer timer; public Form1() { InitializeComponent(); // 初始化Timer对象 timer = new System.Windows.Forms.Timer(); // 设置计时器间隔为一分钟(60000毫秒) timer.Interval = 45000; // 绑定计时器的Tick事件 timer.Tick += new EventHandler(Timer_Tick); // 启动计时器 timer.Start(); LoadJavaYml(); } private void Form1_Load(object sender, EventArgs e) { } private void LoadJavaYml() { string ymlPath = "D:/application.yml"; string ymlContent = string.Empty; if (File.Exists(ymlPath)) { ymlContent=File.ReadAllText(ymlPath); textBox_javayml.AppendText(ymlContent); } } public async Task DownloadFileAsync(string URL, string filePath, int timeoutMilliseconds = 60000, int maxRetries = 3) { float percent = 0; System.IO.FileStream so = null; DateTime lastProgressUpdate = DateTime.Now; int retries = 0; using (HttpClient client = new HttpClient()) { client.Timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds); while (retries < maxRetries) { try { System.Windows.Forms.ProgressBar prog = progressBar_jindu; var response = await client.GetAsync(URL, HttpCompletionOption.ResponseHeadersRead); response.EnsureSuccessStatusCode(); long totalBytes = response.Content.Headers.ContentLength ?? -1; if (prog != null) { prog.Invoke((MethodInvoker)delegate { prog.Maximum = (int)totalBytes; }); } using (var st = await response.Content.ReadAsStreamAsync()) { so = new System.IO.FileStream(filePath, System.IO.FileMode.Create); long totalDownloadedByte = 0; byte[] by = new byte[1024]; int osize = await st.ReadAsync(by, 0, by.Length); while (osize > 0) { totalDownloadedByte += osize; so.Write(by, 0, osize); if (prog != null) { prog.Invoke((MethodInvoker)delegate { prog.Value = (int)totalDownloadedByte; }); } osize = await st.ReadAsync(by, 0, by.Length); percent = (float)totalDownloadedByte / totalBytes * 100; this.Invoke((MethodInvoker)delegate { label_jindu.Text = "当前补丁下载进度" + percent.ToString("F2") + "%"; }); // 更新进度检查时间 lastProgressUpdate = DateTime.Now; // 检查进度是否长时间未更新 if ((DateTime.Now - lastProgressUpdate).TotalMilliseconds > timeoutMilliseconds) { textBox_debug.AppendText("下载进度长时间未更新"+ Environment.NewLine); throw new TimeoutException("下载进度长时间未更新"); } } // 下载完成,退出循环 break; } } catch (Exception ex) { retries++; if (retries >= maxRetries) { // 达到最大重试次数,抛出异常 this.Invoke((MethodInvoker)delegate { textBox_debug.AppendText(ex.Message + Environment.NewLine); }); throw; } else { // 等待一段时间后重试 await Task.Delay(1000); } } finally { if (so != null) { so.Close(); so.Dispose(); } } } } } private void button_down_Click(object sender, EventArgs e) { checkVersion(true); //startJava(); // //KillJava.TerminateProcessOnPort(28899); } private async Task downLoad() { try { string version = string.Empty; this.Invoke((MethodInvoker)delegate { version=label_version.Text; }); string fileName = "jeecg-system-start-" + version + ".jar"; string filePath = "D:/" + fileName; string downurl = textBox_version_url.Text + "/" + fileName; Console.WriteLine(downurl); await DownloadFileAsync(downurl, filePath); this.Invoke((MethodInvoker)delegate { textBox_debug.AppendText("下载完成:"+ filePath + Environment.NewLine); }); } catch (System.Exception ex) { this.Invoke((MethodInvoker)delegate { textBox_debug.AppendText(ex.Message+ Environment.NewLine); }); } } private async void checkVersion(bool isAuot) { try { WebClient client = new WebClient(); string version = client.DownloadString(textBox_version_url.Text + "/jv.txt"); Console.WriteLine(version); this.Invoke((MethodInvoker)delegate { label_version.Text = version; }); string fileName = "jeecg-system-start-" + version + ".jar"; string filePath = "D:/" + fileName; //判断文件是否存在 if (File.Exists(filePath)) { if (checkMd5()) { // 文件存在,提示用户 this.Invoke((MethodInvoker)delegate { textBox_debug.AppendText("文件已存在 不需要更新: " + filePath + Environment.NewLine); }); } else { await downLoad(); //校验md5 if (checkMd5()) { for (int i = 0; i < 10; i++) { KillJava.TerminateProcessOnPort(9000); Thread.Sleep(500); } Thread.Sleep(1000); startJava(); } else { if (isAuot) { // 如果checkMd5不成功,间隔10分钟重新checkVersion System.Threading.Thread.Sleep(5000); checkVersion(true); } } } } else { await downLoad(); //校验md5 if (checkMd5()) { for (int i = 0; i < 10; i++) { KillJava.TerminateProcessOnPort(9000); Thread.Sleep(500); } Thread.Sleep(1000); startJava(); } else { if (isAuot) { // 如果checkMd5不成功,间隔10分钟重新checkVersion System.Threading.Thread.Sleep(5000); checkVersion(true); } } } } catch (System.Exception ex) { this.Invoke((MethodInvoker)delegate { textBox_debug.AppendText(ex.Message + Environment.NewLine); }); if (isAuot) { // 如果checkMd5不成功,间隔10分钟重新checkVersion System.Threading.Thread.Sleep(5000); checkVersion(true); } } } private bool checkMd5() { string version = string.Empty; this.Invoke((MethodInvoker)delegate { version=label_version.Text; }); WebClient client = new WebClient(); string md5txt = client.DownloadString(textBox_version_url.Text + "/jeecg-system-start-" + version + ".jar.txt"); string fileName = "jeecg-system-start-" + version + ".jar"; string filePath = "D:/" + fileName; using (var md5 = MD5.Create()) { using (var stream = System.IO.File.OpenRead(filePath)) { byte[] hash = md5.ComputeHash(stream); string md5Hash = BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant(); string outputFile = filePath + ".txt"; string outputContent = $"File: {filePath}\nMD5: {md5Hash}\n"; textBox_debug.AppendText("本地md5:"+md5Hash+ Environment.NewLine+"远程md5:"+md5txt + Environment.NewLine); textBox_debug.AppendText(outputContent); if (md5txt.Equals(md5Hash)) { textBox_debug.AppendText("校验成功" + Environment.NewLine); return true; } else { textBox_debug.AppendText("校验失败" + Environment.NewLine); return false; } } } } private void startJava() { //保存javayml string ymlPath = "D:/application.yml"; File.WriteAllText(ymlPath, textBox_javayml.Text); string version = string.Empty; this.Invoke((MethodInvoker)delegate { version = label_version.Text; }); string jarFilePath = "D:/" + "jeecg-system-start-" + version + ".jar"; string additionalArgs = "--spring.config.location=D:/application.yml"; // 例如:"--option value" ProcessStartInfo processStartInfo = new ProcessStartInfo(); processStartInfo.FileName = "cmd.exe"; processStartInfo.Arguments = $"/k java -jar {jarFilePath} {additionalArgs}"; processStartInfo.UseShellExecute = true; Process process = new Process(); process.StartInfo = processStartInfo; process.Start(); } // Timer的Tick事件处理方法 private void Timer_Tick(object sender, EventArgs e) { // 获取当前时间 DateTime now = DateTime.Now; // 判断当前时间是否为12点20分 if (now.Hour == 2 && now.Minute == 22) { // 调用需要执行的方法 checkVersion(true); } } } } ``` ``` using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace AutoUp { internal class KillJava { public static void TerminateProcessOnPort(int targetPort) { try { // 获取 netstat 输出 var netstatOutput = GetNetstatOutput(); // 解析 netstat 输出以找到目标端口的进程ID int processId = GetProcessIdFromNetstatOutput(netstatOutput, targetPort); if (processId != -1) { // 获取并终止进程 Process process = Process.GetProcessById(processId); if (process != null && process.ProcessName.ToLower().Contains("java")) { Console.WriteLine($"Terminating process {process.ProcessName} (PID: {processId}) using port {targetPort}"); process.Kill(); Console.WriteLine("Process terminated successfully."); } else { Console.WriteLine($"No Java process found using port {targetPort}"); } } else { Console.WriteLine($"No process found using port {targetPort}"); } } catch (Exception ex) { Console.WriteLine($"An error occurred: {ex.Message}"); } } private static string GetNetstatOutput() { ProcessStartInfo startInfo = new ProcessStartInfo("netstat", "-ano"); startInfo.RedirectStandardOutput = true; startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; using (Process process = Process.Start(startInfo)) { using (System.IO.StreamReader reader = process.StandardOutput) { return reader.ReadToEnd(); } } } private static int GetProcessIdFromNetstatOutput(string netstatOutput, int targetPort) { string[] lines = netstatOutput.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); string pattern = $@":{targetPort}\s+.*\s+(\d+)"; Regex regex = new Regex(pattern); foreach (var line in lines) { Match match = regex.Match(line); if (match.Success) { return int.Parse(match.Groups[1].Value); } } return -1; // 未找到 } } } ``` [/login] 该部分仅登录用户可见 最后修改:2024 年 07 月 26 日 © 允许规范转载 打赏 赞赏作者 赞 如果觉得我的文章对你有用,请随意赞赏