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(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();
        }
    }
}

 

你可能感兴趣的:(winform自动更新,版本更新,Winform)