最近需要给一个小程序加上一个自动升级功能,由于这种功能比较通用也比较独立,所以发出来,以备后用。
截图如下:
代码如下:
入口函数的时候判断是否需有新版本,有则启动下载窗口,然后启动目标程序。
using System; using System.Collections.Generic; using System.Windows.Forms; using System.IO; using System.Net; using System.Diagnostics; namespace FileUpdate { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); try { string verO = ""; string exe = "ScannerPC.exe"; string url = "http://localhost:6564/"; string txt = "Update.txt"; using(var fs = File.Open(txt, FileMode.OpenOrCreate)) using (StreamReader read = new StreamReader(fs)) { verO = read.ReadLine(); if (verO == null) verO = ""; } WebClient webClient = new WebClient(); var Ver = webClient.DownloadString(url + "ver.txt"); if (Ver != verO) { var form = new Form1(Ver,url,exe); Application.Run(form); } ProcessStartInfo info = new ProcessStartInfo(); info.FileName = exe; info.WindowStyle = ProcessWindowStyle.Normal; Process pro = Process.Start(info); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } }
主窗口使用webclient的DownloadFileAsync异步方法下载http文件(不支持断点续传)
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Net; using System.Text; using System.Windows.Forms; namespace FileUpdate { public partial class Form1 : Form { WebClient webClient = new WebClient(); string url = ""; string exePath = ""; string ver = ""; public Form1(string ver,string url,string exe) { this.ver = ver; this.url = url; exePath = exe; InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { try { webClient.DownloadFileCompleted += webClient_DownloadFileCompleted; webClient.DownloadProgressChanged += webClient_DownloadProgressChanged; webClient.DownloadFileAsync(new Uri(url + exePath), exePath); } catch (Exception ex) { MessageBox.Show(ex.Message); Close(); } } void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { progressBar1.Value = e.ProgressPercentage; } void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { if(e.Error != null) { MessageBox.Show("下载文件出错:"+e.Error.Message); } else { using (var writer = new StreamWriter("Update.txt")) { writer.WriteLine(ver); } } Close(); } } }
只支持单个文件更新,没有写多文件支持,也没有加入zip解压这种功能,如果有兴趣可自行添加。可以直接做为程序的启动器,也可以在主程序里面直接调用该程序更新。看起来有点像某些黑客工具的远程下载功能的样子(小),博客文章太少了,只能滥竽充数了o(╯□╰)o
源码:下载