程序更新小功能据


using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace BaobaoAutoUpdate
{
    public partial class Form1 : Form
    {
        const string serviceAddressFileName = "ServiceAddress.txt";
        const string versionFileName = "Version.txt";
        const string unrarPathFileName = "UnrarPath.txt";
        string unrarPath = "./";//解压文件存放目录,程序的目录
        string downloadFileName = "";//下载的文件名

        //文件下载地址
        private string ServiceAddress
        {
            get
            {
                return txtURL.Text;
            }
        }

        private string ConfigPath
        {
            get
            {
                return Environment.CurrentDirectory + "/Config/";
            }
        }

        // string serviceAddress = "http://192.168.1.104/";
        string url4DownloadFileName = "http://192.168.1.104/BBAUService/DownloadFile.html";  //从这里获取需要下载的文件名称
        string url4NewVersion = "http://192.168.1.104/BBAUService/Version.html"; //从这里获取服务器版本号

        //下载文件存放目录
        string downloadTempPath = Environment.CurrentDirectory + "/Download/";

        //下载文件保存名称
        //string rarFileName = "a.rar";

        //RAR压缩程序路径
        string rarExePath = Environment.CurrentDirectory + "/WinRAR/WinRAR.exe";

        //版本号
        string versionNoOld = "";//本地的
        string versionNoNew = "";//服务器的

        public Form1()
        {
            InitializeComponent();

            string serviceAddress = GetSringFromFile(ConfigPath + "/" + serviceAddressFileName); //获取服务地址 
            versionNoOld = GetSringFromFile(ConfigPath + "/" + versionFileName); //获取本地版本号
            unrarPath = GetSringFromFile(ConfigPath + "/" + unrarPathFileName); //
            if (isNull(unrarPath))
            {
                string currentPath = Environment.CurrentDirectory;
                unrarPath = currentPath.Substring(0, currentPath.LastIndexOf("\\"));
            }
            txtURL.Text = serviceAddress;
            txtSavePath.Text = unrarPath;
            lblVersionNoOld.Text = versionNoOld;

            this.Load += Form1_Load;
            btnCheck.Focus();
        }

        void Form1_Load(object sender, EventArgs e)
        {
            btnCheck_Click(null, null);//检查新版本
        }

        //保存服务地址
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                BaobaoUtil.SaveStringToFile(txtURL.Text, ConfigPath, serviceAddressFileName);
                BaobaoUtil.SaveStringToFile(txtSavePath.Text, ConfigPath, unrarPathFileName);
            }
            catch (Exception ex)
            {
                BeginInvoke(new Del_DoCheck_Msg(ShowMsg), "保存文件失败失败: " + ex.Message);
            }
        }

        //检查更新
        private void btnCheck_Click(object sender, EventArgs e)
        {
            if (isNull(ServiceAddress))
            {
                lblMsg.Text = "服务地址不能为空!";
                return;
            }
            url4DownloadFileName = ServiceAddress + "/BBAUService/DownloadName.html";
            url4NewVersion = ServiceAddress + "/BBAUService/Version.html";

            lblVersionNoNew.Text = "";
            lblUpdateFileName.Text = "";
            Thread thread = new Thread(new ThreadStart(DoCheck));
            thread.Start();
        }

        private void DoCheck()
        {
            BeginInvoke(new Del_DoCheck_Msg(CheckBegin), "");

            if (!isNull(url4NewVersion))
            {
                //获取服务器版本号
                try
                {
                    versionNoNew = BaobaoUtil.GetStringFromURL(url4NewVersion);
                    downloadFileName = BaobaoUtil.GetStringFromURL(url4DownloadFileName);
                    BeginInvoke(new Del_DoCheck_Msg(CheckFinish), "");
                }
                catch (Exception e)
                {
                    BeginInvoke(new Del_DoCheck_Msg(ShowMsg), "调用服务[" + url4NewVersion + "]或[" + url4DownloadFileName + "]失败:\n" + e.Message);
                    BeginInvoke(new Del_DoCheck_Msg(CheckFinish), e.Message);
                }
            }
        }

        private void CheckBegin(string msg)
        {
            SetButtonEnabled(false);

            if (isNull(msg))
            {
                lblMsg.Text = "检查中...";
            }
            else
            {
                lblMsg.Text = msg;
            }
        }

        private void CheckFinish(string msg)
        {
            SetButtonEnabled(true);

            lblVersionNoNew.Text = versionNoNew;
            lblUpdateFileName.Text = downloadFileName;
            if (isNull(msg))
            {
                //比对版本号
                if (versionNoOld.CompareTo(versionNoNew) < 0)
                {
                    //提示有新版本
                    lblMsg.Text = "发现新版本!";
                }
                else
                {
                    lblMsg.Text = "已是最新版本!";
                }
            }
            else
            {
                lblMsg.Text = msg;
            }
        }

        //下载,并解压
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (versionNoOld.CompareTo(versionNoNew) < 0)
            {
            }
            else
            {
                if (DialogResult.OK != MessageBox.Show("已是最新版本! 确定进行更新吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information))
                {
                    return;
                }
            }

            if (isNull(downloadFileName))
            {
                ShowMsg("在位置[ " + url4DownloadFileName + " ]没有获取到下载文件名 ");
                return;
            }
            lblMsg.Text = "正在更新程序,下载中...";
            unrarPath = txtSavePath.Text;
            SetButtonEnabled(false);
            Thread thread = new Thread(new ThreadStart(Update2NewVersion));
            thread.Start();
            //BeginInvoke(new Del_DoCheck_Msg(UpdateMsg), "正在更新程序,下载中...");
            //Update2NewVersion();
        }

        //更新程序到新版本,新线程中进行
        private void Update2NewVersion()
        {
            string urlDownload = ServiceAddress + "/BBAUService/" + downloadFileName;
            try
            {
                //TODO 开线程做进度条
                // BaobaoUtil.HttpDownloadFile(urlDownload, downloadTempPath, rarFileName, progressBar1);
                //BaobaoUtil.HttpDownloadFile2(urlDownload, downloadTempPath, rarFileName, updateProgress);
                HttpDownloadFile(urlDownload, downloadTempPath, downloadFileName);
                //下载完成后,显示解压中
                ShowPro(100);
                BeginInvoke(new Del_DoCheck_Msg(UpdateMsg), "正在更新程序,解压中...");
                if (BaobaoUtil.UnRAR(unrarPath, downloadTempPath, downloadFileName, rarExePath))
                {
                    //保存新的版本号等
                    BeginInvoke(new Del_DoCheck_Msg(UpdateMsg), "正在完成更新...");
                    if (!isNull(versionNoNew))
                    {
                        //保存配置文件
                        btnSave_Click(null, null);
                        //保存新的版本号                       
                        BaobaoUtil.SaveStringToFile(versionNoNew, ConfigPath, versionFileName);
                    }
                }

                BeginInvoke(new Del_DoCheck_Msg(UpdateMsg), "更新完成!");
                ShowPro(-100);
            }
            catch (Exception ex)
            {
                BeginInvoke(new Del_DoCheck_Msg(ShowMsg), "从[" + urlDownload + "]下载失败: " + ex.Message);
            }
        }

        //读取文件中的文本
        private string GetSringFromFile(string path)
        {
            StreamReader sRead = null;
            try
            {
                if (File.Exists(path))
                {
                    sRead = new StreamReader(path);
                    string result = sRead.ReadLine().Trim();
                    return result;
                }
            }
            catch (Exception e)
            {
                BeginInvoke(new Del_DoCheck_Msg(ShowMsg), "读取文件失败失败: " + e.Message);
            }
            finally
            {
                if (null != sRead)
                {
                    sRead.Close();
                }
            }
            return "";
        }

        private void SetButtonEnabled(bool enabled)
        {
            btnCheck.Enabled = enabled;
            btnUpdate.Enabled = enabled;
        }

        public delegate void Del_DoCheck_Msg(String msg);
        //提示对话框
        private void ShowMsg(string msg)
        {
            lblMsg.Text = msg;
            MessageBox.Show(msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void UpdateMsg(string msg)
        {
            lblMsg.Text = msg;
        }

        public static bool isNull(string str)
        {
            return string.IsNullOrWhiteSpace(str);
        }

        private delegate void ProgressBarShow(int i);
        private void ShowPro(int value)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new ProgressBarShow(ShowPro), value);
            }
            else
            {
                if (value == -100)
                {
                    SetButtonEnabled(true);
                    progressBar1.Value = 0;
                }
                else
                {
                    progressBar1.Value = value;
                }
            }
        }

        public string HttpDownloadFile(string url, string savePath, string saveFileName)
        {

            Directory.CreateDirectory(savePath);//创建目录,有目录了会忽略
            string filePath = savePath + "/" + saveFileName; //保存的文件的绝对路径
            Stream responseStream = null;
            Stream stream = null;
            HttpWebResponse response = null;
            try
            {
                // 设置参数
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                long resLength = response.ContentLength; //总大小
                string resType = response.ContentType;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                responseStream = response.GetResponseStream();
                //创建本地文件写入流
                stream = new FileStream(filePath, FileMode.Create);
                byte[] bArr = new byte[102400]; //一次读取 100K 
                int size = responseStream.Read(bArr, 0, (int)bArr.Length);  //一次读取 100K 
                long dowLength = 0;  //已经下载的大小
                while (size > 0)
                {
                    stream.Write(bArr, 0, size);
                    size = responseStream.Read(bArr, 0, (int)bArr.Length);  //一次读取 100K 
                    dowLength += size; //已经下载的大小
                    int per = Convert.ToInt32(100 * dowLength / resLength);
                    this.ShowPro(per);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (null != stream)
                {
                    stream.Close();
                }
                if (null != stream)
                {
                    responseStream.Close();
                }
                if (null != response)
                {
                    response.Close();
                }
            }
            return filePath;
        }
    }
}


猜你喜欢

转载自zheyiw.iteye.com/blog/2239536