winform版本自动更新

我们在使用软件的时候经常会遇到升级版本,这也是Winform程序的一个功能,今天就大概说下我是怎么实现的吧(代码有点不完美有小BUG,后面再说)

先说下我的思路:首先在打开程序的时候去拿到我之前在网站上写好的xml里边的版本号,判断是否要更新,之后要更新的话就调用更新的exe(ps:这个是单独出来的,因为更新肯定要覆盖当前的文件,文件运行的时候不能被覆盖),然后下载最新的压缩包到本地,调用7z解压覆盖即可

思路明确了之后就开始写代码(所以说思路很重要啊!!!):

<?xml version="1.0" encoding="utf-8" ?>
<Update>
  <Soft Name="BlogWriter">
    <Verson>1.0.1.2</Verson>
    <DownLoad>http://www.shitong666.cn/BlogWrite.zip</DownLoad>
  </Soft>
</Update>

这是xml,先放到服务器上去

检查更新的代码(我把这个封装成了一个类):

public partial class UpdateForm : Form
    {
        public UpdateForm()
        {
            InitializeComponent();

            this.button1.Enabled = false;
            this.button1.Click += button1_Click;
            this.Text = "更新...";
            UpdateDownLoad();
            // Update();
        }

        void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        public delegate void ChangeBarDel(System.Net.DownloadProgressChangedEventArgs e);

        private void UpdateDownLoad()
        {
            WebClient wc = new WebClient();
            wc.DownloadProgressChanged += wc_DownloadProgressChanged;
            wc.DownloadFileAsync(new Uri("http://www.shitong666.cn/BlogWriter.zip"), "Update.zip");//要下载文件的路径,下载之后的命名
        }
         //  int index = 0;
        void wc_DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
        {
            Action act = () =>
            {
                this.progressBar1.Value = e.ProgressPercentage;
                this.label1.Text = e.ProgressPercentage + "%";

            };
            this.Invoke(act);

            if (e.ProgressPercentage == 100)
            {
                //下载完成之后开始覆盖
                
                  ZipHelper.Unzip();//调用解压的类
                this.button1.Enabled = true;

            }
        }
    }

  解压的类:

public class ZipHelper
    {
        public static string zipFileFullName = "update.zip";
        public static void Unzip()
        {
            string _appPath = new DirectoryInfo(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName).Parent.FullName;

            string s7z = _appPath + @"\7-Zip\7z.exe";
            System.Diagnostics.Process pNew = new System.Diagnostics.Process();
            pNew.StartInfo.FileName = s7z;
            pNew.StartInfo.Arguments = string.Format(" x \"{0}\\{1}\" -y -o\"{0}\"", _appPath, zipFileFullName);
            //x "1" -y -o"2" 这段7z命令的意思: x是解压的意思 "{0}"的位置写要解压文件路径"{1}"这个1的位置写要解压的文件名 -y是覆盖的意思 -o是要解压的位置
            pNew.Start();
            //等待完成
            pNew.WaitForExit();
       //删除压缩包
           File.Delete(_appPath + @"\" + zipFileFullName);
    
        }
    }

  转自:https://www.cnblogs.com/shitong/p/5764200.html

posted @ 2018-10-27 14:20  ৢ清欢ꦿ✿  阅读(1874)  评论(2编辑  收藏  举报