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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM