2013年9月10日 星期二

軟體自動更新程式


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Collections;
using System.Xml;
using System.Configuration;
namespace UpdateTicketKeyin
{
    public partial class Form1 : Form
    {
        //定義全域變數
        WebClient client = new WebClient(); //使用WebClient下載
        int downfilenum = 0;
        int downlistnum = 0;
        ArrayList downlist = new ArrayList();
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            init();  //初始化
        }
        //初始化
        private void init()
        {
            string curdir = Application.StartupPath;
            string xmlPath = ConfigurationSettings.AppSettings["xmlPath"].ToString();
            DownLoad(xmlPath, curdir + @"\temp\Update.xml", false); //同步下載遠端文件 
            string thePreUpdateDate = GetTheLastUpdateTime(curdir); //本地端版本訊息
            string theLastsUpdateDate = GetTheLastUpdateTime(curdir + @"\temp\"); //遠端下載到本地端後的版本訊息
            if (thePreUpdateDate == "") thePreUpdateDate = "2000-01-01";
            //比較應用程式的更新日期
            if (Convert.ToDateTime(thePreUpdateDate) >= Convert.ToDateTime(theLastsUpdateDate))
            {
                //MessageBox.Show("當前軟體已經是最新的,歡迎使用!", "系統提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                final();
            }
            else
            {
                MessageBox.Show("發現新版本,軟體即將自動升級...", "系統提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //關閉原有應用程式的所有執行程序
                System.Diagnostics.Process[] proc = System.Diagnostics.Process.GetProcessesByName("TicketKeyin");
                foreach (System.Diagnostics.Process pro in proc)
                {
                    pro.Kill();
                }
                downlist = GetDownFileList(curdir + @"\temp"); //獲取需要下載的文件列表
                downlistnum = downlist.Count;
                if (downlistnum > 0) DownLoadFile(downlist[0].ToString()); //非同步下載第一個
            }
        }
        private void final()
        {
            string curdir = Application.StartupPath;
            DirectoryInfo theFolder = new DirectoryInfo(curdir + @"\temp");
            if (theFolder.Exists)
            {
                foreach (FileInfo theFile in theFolder.GetFiles())
                {
                    //如果臨時文件夾下存在與應用程式所在目錄下的文件同名的文件,則刪除應用程式目錄下的文件  
                    if (File.Exists(curdir + "\\" + Path.GetFileName(theFile.FullName)))
                        File.Delete(curdir + "\\" + Path.GetFileName(theFile.FullName));
                    //將臨時文件夾的文件移到應用程式所在的目錄下  
                    File.Move(theFile.FullName, curdir + "\\" + Path.GetFileName(theFile.FullName));
                }
            }
            if (Directory.Exists(curdir + @"\temp\")) Directory.Delete(curdir + @"\temp\", true); //刪除臨時目錄
            //啟動安裝程式 
            this.label1.Text = "正在啟動程式....";
            System.Diagnostics.Process.Start(curdir + @"\Keyin.exe");
            this.Close();
        }
        private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            //下載過程中
            int a = e.ProgressPercentage;
            progressBar1.Value = a;
            label1.Text = a + "% 下載中... ";
        }
        private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            //下載完成時
            downfilenum++;
            if (client != null) { client.CancelAsync(); }
            if (downfilenum < downlistnum) DownLoadFile(downlist[downfilenum].ToString());  //下載剩餘的
            if (downfilenum == downlistnum) { final(); }  //完成時要處理的程序
        }
        //獲取本地的版本訊息
        private string GetTheLastUpdateTime(string Dir)
        {
            string LastUpdateTime = "";
            string AutoUpdaterFileName = Dir + @"\Update.xml";
            if (!File.Exists(AutoUpdaterFileName))
            {
                return LastUpdateTime;
            }
            //打開xml文件
            FileStream myFile = new FileStream(AutoUpdaterFileName, FileMode.Open);
            //xml文件閱讀器
            XmlTextReader xml = new XmlTextReader(myFile);
            while (xml.Read())
            {
                if (xml.Name == "UpdateTime")
                {
                    //獲取升級文件的最後一次更新日期
                    LastUpdateTime = xml.GetAttribute("Date");
                    break;
                }
            }
            xml.Close();
            myFile.Close();
            return LastUpdateTime;
        }
        //獲取臨時文件裡的下載文件地址
        private ArrayList GetDownFileList(string Dir)
        {
            int Count = 0;
            ArrayList List = ReadXmlFile(Dir + "\\Update.xml", "UpdateFile", "FileName", ref Count);
            return List;
        }
        //讀取XML中要更新的所有文件名
        private ArrayList ReadXmlFile(string Path, string NodeName, string Name, ref int Count)
        {
            ArrayList List = new ArrayList();
            if (!File.Exists(Path))
            {
                return null;
            }
            //打開xml文件
            FileStream myFile = new FileStream(Path, FileMode.Open);
            //xml文件閱讀器
            XmlTextReader xml = new XmlTextReader(myFile);
            while (xml.Read())
            {
                if (xml.Name == NodeName)
                {
                    //獲取升級文件的最後一次更新日期
                    List.Add(xml.GetAttribute(Name));
                }
            }
            xml.Close();
            myFile.Close();
            return List;
        }
        //HTTP方式下載遠端檔案並保存到本地端
        private void DownLoad(string downAddress, string savePath, Boolean Async)
        {
            DirectoryInfo di = Directory.GetParent(savePath);
            if (!di.Exists) di.Create();
            WebClient client = new WebClient();  //再次 new 避免WebClient不能I/O並存         
            if (Async)
            {
                //非同步下載
                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                client.DownloadFileAsync(new Uri(downAddress), savePath);
            }
            else
            {
                client.DownloadFile(new Uri(downAddress), savePath);
            }
        }
        //下載檔案
        private void DownLoadFile(string url)
        {
            string curdir = Application.StartupPath;
            string[] arr = url.Split('/');
            string filename = arr[arr.Count() - 1];
            label2.Text = filename;
            DownLoad(url, curdir + @"\temp\" + filename, true);  //非同步下載遠端檔案
        }
    }
}

沒有留言:

張貼留言