C#实现Winform程序自动进行版本升级更新
一.首先新建一个Wnform主程序TestMainProgarm,界面如下:
通过AssemblyInfo.cs文件查看程序版本:
[assembly: AssemblyVersion("1.0.0.0")][assembly: AssemblyFileVersion("1.0.0.0")]
string ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();可以获取版本号;
我们可以在主程序运行前检查运行程序的版本和服务器上的版本是否一致,还是版本比较低;主程序代码如下:
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using System.Windows.Forms;using Update;namespace TestMainProgarm{static class Program{/// <summary>/// 应用程序的主入口点。/// </summary>[STAThread]static void Main(){if (checkUpdateLoad()){Application.Exit();return;}Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(new FrmMain());}public static bool checkUpdateLoad(){bool result = false;SoftUpdate app = new SoftUpdate(Application.ExecutablePath, "TestMainProgarm");try{if (app.IsUpdate && MessageBox.Show("检查到新版本,是否更新?", "版本检查", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes){string path = Application.StartupPath.Replace("program", "");System.Diagnostics.Process process = new System.Diagnostics.Process();process.StartInfo.FileName = "autoUpdate.exe";process.StartInfo.WorkingDirectory = path;//要掉用得exe路径例如:"C:\windows";process.StartInfo.CreateNoWindow = true;process.Start();result = true;}else{result = false;}}catch (Exception ex){MessageBox.Show(ex.Message);result = false;}return result;}}}
二.检查程序版本的类SoftUpdate:
using System;using System.Collections.Generic;using System.IO;using System.Linq;using ;using System.Reflection;using System.Text;using System.Threading.Tasks;using System.Xml;namespace Update{/// <summary> /// 更新完成触发的事件 /// </summary> public delegate void UpdateState();/// <summary> /// 程序更新 /// </summary> public class SoftUpdate{private string download;private const string updateUrl = "http://192.168.1.63:8050/update.xml";//升级配置的XML文件地址 #region 构造函数public SoftUpdate() {}/// <summary> /// 程序更新 /// </summary> /// <param name="file">要更新的文件</param> public SoftUpdate(string file, string softName){this.LoadFile = file;this.SoftName = softName;}#endregion#region 属性private string loadFile;private string newVerson;private string softName;private bool isUpdate;/// <summary> /// 或取是否需要更新 /// </summary> public bool IsUpdate{get{checkUpdate();return isUpdate;}}/// <summary> /// 要检查更新的文件 /// </summary> public string LoadFile{get {return loadFile; }set {loadFile = value; }}/// <summary> /// 程序集新版本 /// </summary> public string NewVerson{get {return newVerson; }}/// <summary> /// 升级的名称 /// </summary> public string SoftName{get {return softName; }set {softName = value; }}private string _finalZipName = string.Empty;public string FinalZipName{get {return _finalZipName; }set {_finalZipName = value; }}#endregion/// <summary> /// 更新完成时触发的事件 /// </summary> public event UpdateState UpdateFinish;private void isFinish(){if (UpdateFinish != null)UpdateFinish();}/// <summary> /// 下载更新 /// </summary> public void Update(){try{if (!isUpdate)return;WebClient wc = new WebClient();string filename = "";string exten = download.Substring(download.LastIndexOf("."));if (loadFile.IndexOf(@"\") == -1)filename = "Update_" + Path.GetFileNameWithoutExtension(loadFile) + exten;elsefilename = Path.GetDirectoryName(loadFile) + "\\Update_" + Path.GetFileNameWithoutExtension(loadFile) + exten;FinalZipName = filename;//wc.DownloadFile(download, filename);wc.DownloadFileAsync(new Uri(download), filename);wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);wc.DownloadFileCompleted += new ponentModel.AsyncCompletedEventHandler(wc_DownloadFileCompleted);//wc.Dispose();}catch{throw new Exception("更新出现错误,网络连接失败!");}}void wc_DownloadFileCompleted(object sender, ponentModel.AsyncCompletedEventArgs e){(sender as WebClient).Dispose();isFinish();}void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e){//System.Diagnostics.Debug.WriteLine(e.ProgressPercentage);monMethod.autostep = e.ProgressPercentage;//Thread.Sleep(100);}/// <summary> /// 检查是否需要更新 /// </summary> public void checkUpdate(){try{WebClient wc = new WebClient();Stream stream = wc.OpenRead(updateUrl);XmlDocument xmlDoc = new XmlDocument();xmlDoc.Load(stream);XmlNode list = xmlDoc.SelectSingleNode("Update");foreach (XmlNode node in list){if (node.Name == "Soft" && node.Attributes["Name"].Value.ToLower() == SoftName.ToLower()){foreach (XmlNode xml in node){if (xml.Name == "Verson")newVerson = xml.InnerText;elsedownload = xml.InnerText;}}}Version ver = new Version(newVerson);Version verson = Assembly.LoadFrom(loadFile).GetName().Version;int tm = pareTo(ver);if (tm >= 0)isUpdate = false;elseisUpdate = true;}catch (Exception ex){throw new Exception("更新出现错误,请确认网络连接无误后重试!");}}/// <summary> /// 获取要更新的文件 /// </summary> /// <returns></returns> public override string ToString(){return this.loadFile;}}}
三.自动升级的程序:
代码如下:
using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.IO;using System.Linq;using System.Runtime.InteropServices;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using Update;namespace autoUpdate{public partial class Form1 : Form{[DllImport("zipfile.dll")]public static extern int MyZip_ExtractFileAll(string zipfile, string pathname);public Form1(){InitializeComponent();//清除之前下载来的rar文件if (File.Exists(Application.StartupPath + "\\Update_autoUpdate.zip")){try{File.Delete(Application.StartupPath + "\\Update_autoUpdate.zip");}catch (Exception){}}if (Directory.Exists(Application.StartupPath + "\\autoupload")){try{Directory.Delete(Application.StartupPath + "\\autoupload", true);}catch (Exception){}}//检查服务端是否有新版本程序checkUpdate();timer1.Enabled = true;}SoftUpdate app = new SoftUpdate(Application.ExecutablePath, "TestMainProgarm");public void checkUpdate(){app.UpdateFinish += new UpdateState(app_UpdateFinish);try{if (app.IsUpdate){app.Update();}else{MessageBox.Show("未检测到新版本!");Application.Exit();}}catch (Exception ex){MessageBox.Show(ex.Message);}}void app_UpdateFinish(){//解压下载后的文件string path = app.FinalZipName;if (File.Exists(path)){//后改的 先解压滤波zip植入ini然后再重新压缩string dirEcgPath = Application.StartupPath + "\\" + "autoupload";if (!Directory.Exists(dirEcgPath)){Directory.CreateDirectory(dirEcgPath);}//开始解压压缩包MyZip_ExtractFileAll(path, dirEcgPath);try{//复制新文件替换旧文件DirectoryInfo TheFolder = new DirectoryInfo(dirEcgPath);foreach (FileInfo NextFile in TheFolder.GetFiles()){File.Copy(NextFile.FullName, Application.StartupPath + "\\program\\" + NextFile.Name, true);}Directory.Delete(dirEcgPath, true);File.Delete(path);//覆盖完成 重新启动程序path = Application.StartupPath + "\\program";System.Diagnostics.Process process = new System.Diagnostics.Process();process.StartInfo.FileName = "TestMainProgarm.exe";process.StartInfo.WorkingDirectory = path;//要掉用得exe路径例如:"C:\windows";process.StartInfo.CreateNoWindow = true;process.Start();Application.Exit();}catch (Exception){MessageBox.Show("请关闭系统在执行更新操作!");Application.Exit();}}}private void timer1_Tick(object sender, EventArgs e){label2.Text = "下载文件进度:" + monMethod.autostep.ToString() + "%";this.progressBar1.Value = monMethod.autostep;if (monMethod.autostep == 100){timer1.Enabled = false;}}}}
三.先在服务器上放置一个存放软件版本号和最新版程序路径的xml文件,目前网站上的程序时1.0.0.3版本,我是在本机IIS上新建了一个网站进行测试的,网站路径为:http://192.168.1.63:8050/update.xml,xml文件内容如下:
<?xml version="1.0" encoding="utf-8" ?><Update><Soft Name="TestMainProgarm"><Verson>1.0.0.3</Verson><DownLoad>http://192.168.1.63:8050/Update_autoUpdate.zip</DownLoad></Soft></Update>
网站中的文件如下:
最后代码链接:/download/qq_43024228/12116799