C#Winform自動檢測版本更新,下載最新版本

解決思路:

思路1:主程序打開後,先訪問服務器上的版本數據接口,檢查本地版本是否爲最新,如果不是,則打開更新程序,關閉主程序,更新程序下載最新的主程序EXE,替換之前的EXE文件,替換完之後再打開主程序,關閉更新程序。

思路2:以更新程序爲打開入口,先打開更新程序,訪問服務器上的版本數據接口,檢查本地版本是否爲最新,如果不是,則下載最新的主程序EXE,替換之前的主程序EXE文件,替換完之後再打開主程序,關閉更新程序。

注意:本地版本信息放在Config文件中

上代碼

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace UpdateProgram
{
    public partial class Form1 : Form
    {
        string UpdateUrl = "http://更新網址/" + "ATAPI/UpdateExe";//檢測版本更新地址
        string ExeUrl = "http://更新網址/update/exe/";//下載EXE的地址
        string ExeName = "Index";//程序名
        public Form1()
        {
            InitializeComponent();
            
        }
        public void Updatenow()
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(@"" + ExeName + ".exe"); // 寫的是應用程序的路徑
            }
            catch
            {
                MessageBox.Show("當前目錄找不到主程序" + ExeName);
                Close();
                return;
            }
            string retdata = HttpGet(UpdateUrl);
            lg_updateBean updateBean = CYQ.Data.Tool.JsonHelper.ToEntity<lg_updateBean>(retdata);
            int versionid = 0;//當前的版本ID
            string versionname = string.Empty;
            int.TryParse(LoadConfig("VersionID"), out versionid);
            versionname = LoadConfig("VersionName");//當前的版本號
            if (versionid < updateBean.ID)//需要更新
            {
                DialogResult dr = MessageBox.Show("檢測到新版本:" + updateBean.Version + "更新內容:" + updateBean.Remarks + ",當前版本:" + versionname + ",是否更新", "操作提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (DialogResult.Yes == dr)
                {
                    try
                    {
                        System.Net.WebClient client = new System.Net.WebClient();
                        byte[] data = client.DownloadData(ExeUrl + updateBean.ID + "/" + ExeName + ".exe");//下載EXE程序

                        System.Diagnostics.Process[] ps = System.Diagnostics.Process.GetProcesses();//把之前的程序關閉
                        foreach (System.Diagnostics.Process p in ps)
                        {
                            //MessageBox.Show(p.ProcessName);
                            if (p.ProcessName == ExeName || p.ProcessName == (ExeName + ".vshost"))
                            {
                                p.Kill();
                                break;
                            }
                        }

                        string path = Application.StartupPath;
                        FileStream fs = new FileStream(path + "\\" + ExeName + ".exe", FileMode.Create);
                        //將byte數組寫入文件中
                        fs.Write(data, 0, data.Length);
                        fs.Close();
                        MessageBox.Show("更新成功");

                        SaveConfig("VersionID", updateBean.ID.ToString());
                        SaveConfig("VersionName", updateBean.Version);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("更新失敗:" + ex.Message);
                    }
                }
            }
            Close();
            System.Diagnostics.Process.Start(Application.StartupPath + "\\" + ExeName + ".exe");

        }
        public string LoadConfig(string content)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(@"" + ExeName + ".exe"); // 寫的是應用程序的路徑
            try
            {
                return config.AppSettings.Settings[content].Value;
            }
            catch
            {
                return "";
            }

        }
        public void SaveConfig(string content, string value)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(@"" + ExeName + ".exe"); // 寫的是應用程序的路徑
            try
            {
                config.AppSettings.Settings[content].Value = value;
            }
            catch
            {
                config.AppSettings.Settings.Add(content, value);
            }
            config.Save(System.Configuration.ConfigurationSaveMode.Minimal);
        }
        public static string HttpGet(string url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            //request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "*/*";
            request.Timeout = 15000;
            request.AllowAutoRedirect = false;
            WebResponse response = null;
            string responseStr = null;
            try
            {
                response = request.GetResponse();
                if (response != null)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception)
            {
                MessageBox.Show("請檢查當前網絡或者鏈接路徑");
            }
            finally
            {
                request = null;
                response = null;
            }
            return responseStr;
        }
        public partial class lg_updateBean
        {
            public int ID { get; set; }
            public string Version { get; set; }
            public string Remarks { get; set; }

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Updatenow();
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章