已阅读5页,还剩11页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
在WinForm应用程序中实现自动升级功能首先,要确定程序应去哪里下载需要升级的文件。我选择了到指定的网站上去下载,这样比较简单,也通用一些。在网站上,需放置一个当前描述最新文件列表的文件,我估且叫它服务器配置文件。这个文件保存了当前最新文件的版本号(lastversion),大小(size),下载地址(url),本地文件的保存路径(path),还有更新后,程序是否需要重新启动(needRestart)。updateService.xml同时,客户端也保存了一个需要升级的本地文件的列表,形式和服务器配置文件差不多,我们叫它本地配置文件。其中,节点表示是否启用自动升级功能,表示服务器配置文件的地址。update.configtrue/updateService.xml使用自动升级组件的程序在启动时,会去检查这个配置文件。如果发现有配置文件中的文件版本和本地配置文件中描述的文件版本不一致,则提示用户下载。同时,如果本地配置文件中某些文件在服务器配置文件的文件列表中不存在,则说明这个文件已经不需要了,需要删除。最后,当升级完成后,会更新本地配置文件。我们先来看一下如何使用这个组件。在程序的Program.cs的Main函数中:STAThreadstatic void Main() Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);AutoUpdater au = new AutoUpdater();try au.Update(); catch (System.Net.WebException exception) MessageBox.Show(无法找到指定资源nn + exception.Message, 自动升级, MessageBoxButtons.OK, MessageBoxIcon.Error); catch (System.Xml.XmlException exception) MessageBox.Show(下载的升级文件有错误nn + exception.Message, 自动升级, MessageBoxButtons.OK, MessageBoxIcon.Error); catch (System.NotSupportedException exception) MessageBox.Show(升级地址配置错误nn + exception.Message, 自动升级, MessageBoxButtons.OK, MessageBoxIcon.Error); catch (System.ArgumentException exception) MessageBox.Show(下载的升级文件有错误nn + exception.Message, 自动升级, MessageBoxButtons.OK, MessageBoxIcon.Error); catch (System.Exception exception) MessageBox.Show(升级过程中发生错误nn + exception.Message, 自动升级, MessageBoxButtons.OK, MessageBoxIcon.Error); 如上所示,只需要简单的几行代码,就可以实现自动升级功能了。软件运行截图:AutoUpdater.csusing System;using System.Collections.Generic;using System.Diagnostics;using System.IO;using System.Net;using System.Text;using System.Windows.Forms;using System.Xml;using System.Xml.Serialization;namespace MyUpdate / / 自动升级的管理类,负责整体的自动升级功能的实现 / public class AutoUpdater public event ShowHandler OnShow; public delegate void ShowHandler(); private const string fileName = update.config; private readonly string downLoadXML = ; private Config config = null; private bool needRestart = false; public AutoUpdater() / 加载配置文件 config = Config.LoadConfig(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); downLoadXML = Application.StartupPath + + updateService.xml; / / 检查新版本 / / 无法找到指定资源 / 升级地址配置错误 / 下载的升级文件有错误 / 下载的升级文件有错误 / 未知错误 public void Update() / 是否开启了自动更新 if (!config.Enabled) return; / 请求Web服务器,得到当前最新版本的文件列表,格式同本地的update.config。与本地的update.config比较,找到不同版本的文件,生成一个更新文件列表,开始DownloadProgress / 如果启用了自动更新,就需要下载服务器配置文件 WebClient client = new WebClient(); client.Encoding = Encoding.Default; client.DownloadFile(config.ServerUrl, downLoadXML); / 解析服务器配置文件到Dictionary中 Dictionary listRemotFile = ParseRemoteXml(downLoadXML); / 比较服务器配置文件和本地配置文件,找出需要下载的文件和本地需要删除的文件 List downloadList = new List(); / 某些文件不再需要了,删除 List preDeleteFile = new List(); foreach (LocalFile file in config.UpdateFileList) if (listRemotFile.ContainsKey(file.Path) RemoteFile rf = listRemotFilefile.Path; if (rf.LastVer != file.LastVer) downloadList.Add(new DownloadFileInfo(rf.Url, file.Path, rf.LastVer, rf.Size); file.LastVer = rf.LastVer; file.Size = rf.Size; if (rf.NeedRestart) needRestart = true; listRemotFile.Remove(file.Path); else preDeleteFile.Add(file); foreach (RemoteFile file in listRemotFile.Values) downloadList.Add(new DownloadFileInfo(file.Url, file.Path, file.LastVer, file.Size); config.UpdateFileList.Add(new LocalFile(file.Path, file.LastVer, file.Size); if (file.NeedRestart) needRestart = true; / 如果发现有需要下载的文件,则向用户显示这些文件,并提示其是否马上更新。如果用户选择了马上更新,则先删除本地不再需要的文件,然后开始下载更新文件 if (downloadList.Count 0) DownloadConfirm dc = new DownloadConfirm(downloadList); if (this.OnShow != null) this.OnShow(); if (DialogResult.OK = dc.ShowDialog() Process proc = Process.GetProcessesByName(); /关闭原有应用程序的所有进程 foreach (Process pro in proc) pro.Kill(); foreach (LocalFile file in preDeleteFile) string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, file.Path); if (File.Exists(filePath) File.Delete(filePath); config.UpdateFileList.Remove(file); StartDownload(downloadList); private Dictionary ParseRemoteXml(string xml) XmlDocument document = new XmlDocument(); document.Load(xml); Dictionary list = new Dictionary(); foreach (XmlNode node in document.DocumentElement.ChildNodes) list.Add(node.Attributespath.Value, new RemoteFile(node); return list; / / 先调用DownloadProgress下载所有需要下载的文件,然后更新本地配置文件,最后,如果发现某些更新文件需要重新启动应用程序的话,会提示用户重新启动程序。 / private void StartDownload(List downloadList) DownloadProgress dp = new DownloadProgress(downloadList); if (dp.ShowDialog() = DialogResult.OK) / 更新成功 config.SaveConfig(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); if (needRestart) MessageBox.Show(程序需要重新启动才能应用更新,请点击确定重新启动程序。, 自动更新, MessageBoxButtons.OK, MessageBoxIcon.Information); Process.Start(Application.ExecutablePath); Environment.Exit(0); / / 配置类,负责管理本地配置文件 / public class Config private bool enabled = true; public bool Enabled get return enabled; set enabled = value; private string serverUrl = ; public string ServerUrl get return serverUrl; set serverUrl = value; private List updateFileList = new List(); public List UpdateFileList get return updateFileList; set updateFileList = value; public static Config LoadConfig(string file) XmlSerializer xs = new XmlSerializer(typeof(Config); StreamReader sr = new StreamReader(file); Config config = xs.Deserialize(sr) as Config; sr.Close(); return config; public void SaveConfig(string file) XmlSerializer xs = new XmlSerializer(typeof(Config); StreamWriter sw = new StreamWriter(file); xs.Serialize(sw, this); sw.Close(); / / 表示本地配置文件中的一个文件 / public class LocalFile private string path = ; private string lastver = ; private int size = 0; XmlAttribute(path) public string Path get return path; set path = value; XmlAttribute(lastver) public string LastVer get return lastver; set lastver = value; XmlAttribute(size) public int Size get return size; set size = value; public LocalFile() public LocalFile(string path, string ver, int size) this.path = path; this.lastver = ver; this.size = size; / / 表示服务器配置文件中的一个文件 / public class RemoteFile private string path = ; private string url = ; private string lastver = ; private int size = 0; private bool needRestart = false; public string Path get return path; public string Url get return url; public string LastVer get return lastver; public int Size get return size; public bool NeedRestart get return needRestart; public RemoteFile(XmlNode node) this.path = node.Attributespath.Value; this.url = node.Attributesurl.Value; this.lastver = node.Attributeslastver.Value; this.size = Convert.ToInt32(node.Attributessize.Value); this.needRestart = Convert.ToBoolean(node.AttributesneedRestart.Value); / / 要下载的文件的信息 / public class DownloadFileInfo string downloadUrl = ; string fileName = ; string lastver = ; int size = 0; / / 要从哪里下载文件 / public string DownloadUrl get return downloadUrl; / / 下载完成后要放到哪里去 / public string FileFullName get return fileName; public string FileName get return Path.GetFileName(FileFullName); public string LastVer get return lastver; set lastver = value; public int Size get return size; public DownloadFileInfo(string url, string name, string ver, int size) this.downloadUrl = url; this.fileName = name; this.lastver = ver; this.size = size; DownloadConfirm.csusing System;using System.Collections.Generic;using System.ComponentModel;using System.Drawing;using System.Windows.Forms;namespace MyUpdate / / 一个对话框,向用户显示需要升级的文件的列表,并允许用户选择是否马上升级 / public class DownloadConfirm : Form List downloadFileList = null; public DownloadConfirm(List dfl) InitializeComponent(); downloadFileList = dfl; private void OnLoad(object sender, EventArgs e) foreach (DownloadFileInfo file in this.downloadFileList) ListViewItem item = new ListViewItem(new string file.FileName, file.LastVer, file.Size.ToString() ); this.lvDownloadFile.Items.Add(item); this.Activate(); this.Focus(); / / 必需的设计器变量 / private IContainer components = null; / / 清理所有正在使用的资源 / / 如果应释放托管资源,为true;否则为false protected override void Dispose(bool disposing) if (disposing & (components != null) components.Dispose(); base.Dispose(disposing); / / 设计器支持所需的方法- 不要使用代码编辑器修改此方法的内容 / private void InitializeComponent() this.btnOk = new Button(); this.btnCancel = new Button(); this.lvDownloadFile = new ListView(); this.columnHeader1 = new ColumnHeader(); this.columnHeader2 = new ColumnHeader(); this.columnHeader3 = new ColumnHeader(); this.lblFileUpdate = new Label(); this.SuspendLayout(); / / btnOk / this.btnOk.DialogResult = DialogResult.OK; this.btnOk.Location = new Point(184, 217); this.btnOk.Name = btnOk; this.btnOk.Size = new Size(75, 23); this.btnOk.Text = 马上更新; this.btnOk.UseVisualStyleBackColor = true; / / btnCancel / this.btnCancel.DialogResult = DialogResult.Cancel; this.btnCancel.Location = new Point(265, 217); this.btnCancel.Name = btnCancel; this.btnCancel.Size = new Size(75, 23); this.btnCancel.Text = 以后再说; this.btnCancel.UseVisualStyleBackColor = true; / / lvDownloadFile / this.lvDownloadFile.Columns.AddRange(new ColumnHeader this.columnHeader1, this.columnHeader2, this.columnHeader3); this.lvDownloadFile.Location = new Point(12, 24); this.lvDownloadFile.Name = lvDownloadFile; this.lvDownloadFile.Size = new Size(328, 187); this.lvDownloadFile.UseCompatibleStateImageBehavior = false; this.lvDownloadFile.View = View.Details; this.lvDownloadFile.FullRowSelect = true; / / columnHeader1 / this.columnHeader1.Text = 文件名; this.columnHeader1.Width = 149; / / columnHeader2 / this.columnHeader2.Text = 最新版本; this.columnHeader2.Width = 110; / / columnHeader3 / this.columnHeader3.Text = 大小; this.columnHeader3.Width = 65; / / lblFileUpdate / this.lblFileUpdate.AutoSize = true; this.lblFileUpdate.Location = new Point(12, 9); this.lblFileUpdate.Name = lblFileUpdate; this.lblFileUpdate.Size = new Size(113, 12); this.lblFileUpdate.Text = 以下文件需要更新:; / / DownloadConfirm / this.AcceptButton = this.btnOk; this.AutoScaleDimensions = new SizeF(6F, 12F); this.AutoScaleMode = AutoScaleMode.Font; this.CancelButton = this.btnCancel; this.ClientSize = new Size(352, 252); this.ControlBox = false; this.Controls.Add(this.lblFileUpdate); this.Controls.Add(this.lvDownloadFile); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOk); this.FormBorderStyle = FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = DownloadConfirm; this.StartPosition = FormStartPosition.CenterScreen; this.Text = 发现新版本; this.Load += new EventHandler(this.OnLoad); this.ResumeLayout(false); this.PerformLayout(); private Button btnOk; private Button btnCancel; private ListView lvDownloadFile; private Label lblFileUpdate; private ColumnHeader columnHeader1; private ColumnHeader columnHeader2; private ColumnHeader columnHeader3; DownloadProgress.csusing System;using System.Collections.Generic;using System.ComponentModel;using System.Drawing;using System.IO;using System.Net;using System.Threading;using System.Windows.Forms;namespace MyUpdate / / 一个对话框,显示下载进度 / public partial class DownloadProgress : Form private bool isFinished = false; private List downloadFileList = null; / new private List downloadedFileList = null; / end new private ManualResetEvent evtDownload = null; private ManualResetEvent evtPerDonwload = null; private WebClient clientDownload = null; public DownloadProgress(List downloadFileList) InitializeComponent(); this.downloadFileList = downloadFileList; private void OnFormClosing(object sender, FormClosingEventArgs e) if (!isFinished & DialogResult.No = MessageBox.Show(当前正在更新,是否取消?, 自动升级, MessageBoxButtons.YesNo, MessageBoxIcon.Question) e.Cancel = true; return; else if (clientDownload != null) clientDown
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 玩具质量检测新人培训试题及答案
- AI机器人智能制造项目环境影响报告书
- 400MWh电网侧新型储能项目投标书
- 2025浙江宁波鄞州区实验小学教育集团(南校区)招聘1人考试笔试备考题库及答案解析
- 2025年芜湖领航文化旅游投资有限公司(筹)工作人员招聘7人考试笔试参考题库附答案解析
- 2025中国华电集团有限公司广东公司所属部分基层企业面向系统内外招聘32人考试笔试备考题库及答案解析
- 2025天津宁河区公益性岗位招聘1人笔试考试备考题库及答案解析
- 2026南方财经全媒体集团校园招聘笔试考试备考试题及答案解析
- 2025安徽芜湖市湾沚区国有资本建设投资(集团)有限公司及其子公司第一批工作人员招聘12人考试笔试备考试题及答案解析
- 2026江苏农林职业技术学院招聘高层次人才(第一批)2人考试笔试备考题库及答案解析
- 建设工程监理知到章节答案智慧树2023年沈阳职业技术学院
- 人力资源管理知到章节答案智慧树2023年湖南大学
- 115个低风险病种ICD-10(2019 v2.0)编码表、专科医院单病种(术种)目录
- 创新创业基础(石河子大学)智慧树知到答案章节测试2023年
- GB/T 8814-1998门、窗框用硬聚氯乙烯(PVC)型材
- GB/T 1770-2008涂膜、腻子膜打磨性测定法
- GA 576-2005防尾随联动互锁安全门通用技术条件
- 高中数学《基于问题链的数学教学探索》课件
- 2021-2022学年人教版科学五年级上册第9课《显微镜下的细胞》(教案)
- 道路运输企业岗位安全责任清单
- 五年级上册数学课件-6.6 数学广场-编码 ▏沪教版 (共32张PPT)
评论
0/150
提交评论