winform 在线升级

昨天看了别人的在线升级程序代码,然后复制代码实验了下,发现客户端貌似只能下载文件不能下载文件夹,所以简单的修改了下,循环下载文件夹下的文件

服务器端代码

<%@ WebHandler Language="C#" Class="UpdateSize" %>

using System; 
using System.Web; 
using System.IO;

public class UpdateSize : IHttpHandler { 
    public void ProcessRequest (HttpContext context) 
    {
        len = 0;
        string dirPath = context.Server.MapPath("~/AutoUpdater/"); 
        context.Response.ContentType = "text/xml"; 
        context.Response.Expires = -1; 
        context.Response.Write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"); 
        context.Response.Write("<UpdateSize Size=\"" + GetUpdateSize(dirPath) + "\" />"); 
        context.Response.End(); 
    }

    /// <summary> 
    /// 获取所有下载文件大小 
    /// </summary> 
    /// <returns>返回值</returns> 
    static long len = 0;
    private static long GetUpdateSize(string dirPath) 
    { 
        //判断文件夹是否存在,不存在则退出 
        if (!Directory.Exists(dirPath)) 
            return 0;
        DirectoryInfo di = new DirectoryInfo(dirPath); 
        //获取所有文件大小 
        //foreach (FileInfo fi in di.GetFiles()) 
        foreach (FileSystemInfo fi in di.GetFileSystemInfos()) 
        { 
            //剔除升级数据文件 
            if (fi.Name != "AutoUpdater.xml")
            {
                GetUpdateSize(fi.FullName);
                
                FileInfo f = fi as FileInfo;
                if (f!=null)
                {
                    len += f.Length; 
                }
            }
        }
        return len; 
    }

    public bool IsReusable 
    { 
        get 
        { 
            return false; 
        } 
    }

}

AutoUpdater目录下的AutoUpdater.xml文件代码

<?xml version="1.0" encoding="utf-8" ?>
<AutoUpdater>
  <UpdateInfo>
    <!--升级文件的更新日期-->
    <UpdateTime Date = "2008-09-06"/>
  </UpdateInfo>
  <!--升级文件列表-->
 <UpdateFileList>
    <UpdateFile>1\3.txt</UpdateFile>
  </UpdateFileList>
<UpdateFileList>
    <UpdateFile>1\4.txt</UpdateFile>
  </UpdateFileList>

  <UpdateFileList>
    <UpdateFile>1.txt</UpdateFile>
  </UpdateFileList>
  <UpdateFileList>
    <UpdateFile>2.txt</UpdateFile>
  </UpdateFileList>
</AutoUpdater>

客户端代码

using System;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Windows.Forms.Design; 

namespace QWeiXinPrinter
{
    public partial class AutoUpdater : Form
    {
        private WebClient downWebClient = new WebClient();
        private static string dirPath;
        private static long size;//所有文件大小 
        private static int count;//文件总数 
        private static string[] fileNames;
        private static int num;//已更新文件数 
        private static long upsize;//已更新文件大小 
        private static string fileName;//当前文件名 
        private static long filesize;//当前文件大小 
        public AutoUpdater()
        {
            InitializeComponent();
        }
        private void AutoUpdater_Load(object sender, EventArgs e)
        {
            dirPath = GetConfigValue("conf.config", "Url");
            string thePreUpdateDate = GetTheLastUpdateTime(dirPath);
            string localUpDate = GetConfigValue("conf.config", "UpDate");
            if (!String.IsNullOrEmpty(thePreUpdateDate) && !String.IsNullOrEmpty(localUpDate))
            {
                if (DateTime.Compare(
                    Convert.ToDateTime(thePreUpdateDate, CultureInfo.InvariantCulture),
                    Convert.ToDateTime(localUpDate, CultureInfo.InvariantCulture)) > 0)
                {
                    if (Directory.Exists(Application.StartupPath + "\\"+"AutoUpdater"))
                    {            
                        Directory.Move(Application.StartupPath + "\\" + "AutoUpdater", Application.StartupPath + "\\" + "AutoUpdater" + DateTime.Now.Ticks);//备份原先的升级文件
                        Directory.CreateDirectory(Application.StartupPath + "\\" + "AutoUpdater");
                    }
                    else
                    {
                        Directory.CreateDirectory(Application.StartupPath + "\\" + "AutoUpdater");
                    }
                    UpdaterStart();
                }
                else
                {
                    UpdaterClose();
                }
            }
            else
            {
                UpdaterClose();
            }
            //UpdaterStart(); 
        }

        /// <summary> 
        /// 开始更新 
        /// </summary> 
        private void UpdaterStart()
        {
            try
            {
                float tempf;
                //委托下载数据时事件 
                this.downWebClient.DownloadProgressChanged += delegate(object wcsender, DownloadProgressChangedEventArgs ex)
                {
                    this.label2.Text = String.Format(
                        CultureInfo.InvariantCulture,
                        "正在下载:{0}  [ {1}/{2} ]",
                        fileName,
                        ConvertSize(ex.BytesReceived),
                        ConvertSize(ex.TotalBytesToReceive));
                    filesize = ex.TotalBytesToReceive;
                    tempf = ((float)(upsize + ex.BytesReceived) / size);
                    this.progressBar1.Value = Convert.ToInt32(tempf * 100);
                    this.progressBar2.Value = ex.ProgressPercentage;
                };
                //委托下载完成时事件 
                this.downWebClient.DownloadFileCompleted += delegate(object wcsender, AsyncCompletedEventArgs ex)
                {
                    if (ex.Error != null)
                    {
                        MeBox(ex.Error.Message);
                    }
                    else
                    {//if (File.Exists(Application.StartupPath + "\\" + file_path + fileName))
                        //{
                        //    File.Delete(Application.StartupPath + "\\" + file_path + fileName);
                        //}
                        if (m_files.Length>1)
                        {
                            if (!Directory.Exists(Application.StartupPath + "\\" + file_path))
                            {
                                Directory.CreateDirectory(Application.StartupPath + "\\" + file_path);
                            }
                        }
                       
                        File.Copy(loc_path + file_path+fileName, Application.StartupPath + "\\" + file_path+fileName,true);
                        upsize += filesize;
                        if (fileNames.Length > num)
                        {
                            DownloadFile(num);
                        }
                        else
                        {
                            SetConfigValue("conf.config", "UpDate", GetTheLastUpdateTime(dirPath));
                            UpdaterClose();
                        }
                    }
                };

                size = GetUpdateSize(dirPath + "UpdateSize.ashx");
                if (size == 0)
                    UpdaterClose();
                num = 0;
                upsize = 0;
                UpdateList();
                if (fileNames != null)
                    DownloadFile(0);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary> 
        /// 获取更新文件大小统计 
        /// </summary> 
        /// <param name="filePath">更新文件数据XML</param> 
        /// <returns>返回值</returns> 
        private static long GetUpdateSize(string filePath)
        {
            long len;
            len = 0;
            try
            {
                WebClient wc = new WebClient();
                Stream sm = wc.OpenRead(filePath);
                XmlTextReader xr = new XmlTextReader(sm);
                while (xr.Read())
                {
                    if (xr.Name == "UpdateSize")
                    {
                        len = Convert.ToInt64(xr.GetAttribute("Size"), CultureInfo.InvariantCulture);
                        break;
                    }
                }
                xr.Close();
                sm.Close();
            }
            catch (WebException ex)
            {
                MeBox(ex.Message);
            }
            return len;
        }

        /// <summary> 
        /// 获取文件列表并下载 
        /// </summary> 
        private static void UpdateList()
        {
            string xmlPath = dirPath + "AutoUpdater/AutoUpdater.xml";
            WebClient wc = new WebClient();
            DataSet ds = new DataSet();
            ds.Locale = CultureInfo.InvariantCulture;
            try
            {
                Stream sm = wc.OpenRead(xmlPath);
                ds.ReadXml(sm);
                DataTable dt = ds.Tables["UpdateFileList"];
                StringBuilder sb = new StringBuilder();
                count = dt.Rows.Count;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (i == 0)
                    {
                        sb.Append(dt.Rows[i]["UpdateFile"].ToString());
                    }
                    else
                    {
                        sb.Append("," + dt.Rows[i]["UpdateFile"].ToString());
                    }
                }
                fileNames = sb.ToString().Split(',');
                sm.Close();
            }
            catch (WebException ex)
            {
                MeBox(ex.Message);
            }
        }

        /// <summary> 
        /// 下载文件 
        /// </summary> 
        /// <param name="arry">下载序号</param> 
        string m_file;
        string[] m_files;
        string ser_path;
        string loc_path;
        string file_path;
        private void DownloadFile(int arry)
        {
            try
            {
                num++;
                file_path = "";
                m_file = fileNames[arry];
                m_files = m_file.Split('\\');
                fileName=m_files[m_files.Length-1];
                //fileName = fileNames[arry];
                this.label1.Text = String.Format(
                    CultureInfo.InvariantCulture,
                    "更新进度 {0}/{1}  [ {2} ]",
                    num,
                    count,
                    ConvertSize(size));
                 ser_path = dirPath + "AutoUpdater/";
                 loc_path = Application.StartupPath + "\\AutoUpdater\\";
                //string ser_path = dirPath + "AutoUpdater/" + fileName;
                //string loc_path = Application.StartupPath + "\\AutoUpdater\\" + fileName;
                this.progressBar2.Value = 0;
                foreach (string item in m_files)
                {

                    if (item == m_files[m_files.Length - 1])
                    {
                        //file_path += item;
                    }
                    else
                    {
                        if (!Directory.Exists(loc_path + file_path + item))
                        {
                            Directory.CreateDirectory(loc_path + file_path + item);
                        }
                        file_path += item + "\\";
                    }                
                }
                
                this.downWebClient.DownloadFileAsync(
                    new Uri(ser_path+file_path+fileName),loc_path+file_path+fileName);
            }
            catch (WebException ex)
            {
                MeBox(ex.Message);
            }
        }

        /// <summary> 
        /// 转换字节大小 
        /// </summary> 
        /// <param name="byteSize">输入字节数</param> 
        /// <returns>返回值</returns> 
        private static string ConvertSize(long byteSize)
        {
            string str = "";
            float tempf = (float)byteSize;
            if (tempf / 1024 > 1)
            {
                if ((tempf / 1024) / 1024 > 1)
                {
                    str = ((tempf / 1024) / 1024).ToString("##0.00", CultureInfo.InvariantCulture) + "MB";
                }
                else
                {
                    str = (tempf / 1024).ToString("##0.00", CultureInfo.InvariantCulture) + "KB";
                }
            }
            else
            {
                str = tempf.ToString(CultureInfo.InvariantCulture) + "B";
            }
            return str;
        }

        /// <summary> 
        /// 弹出提示框 
        /// </summary> 
        /// <param name="txt">输入提示信息</param> 
        private static void MeBox(string txt)
        {
            MessageBox.Show(
                txt,
                "提示信息",
                MessageBoxButtons.OK,
                MessageBoxIcon.Asterisk,
                MessageBoxDefaultButton.Button1,
                MessageBoxOptions.DefaultDesktopOnly);
        }

        /// <summary> 
        /// 关闭程序 
        /// </summary> 
        private static void UpdaterClose()
        {
            //try
            //{
            //    System.Diagnostics.Process.Start(Application.StartupPath + "\\QWeiXinPrinter.exe");
            //}
            //catch (Win32Exception ex)
            //{
            //    MeBox(ex.Message);
            //}
            //Application.Exit();
        }

        /// <summary> 
        /// 读取.exe.config的值 
        /// </summary> 
        /// <param name="path">.exe.config文件的路径</param> 
        /// <param name="appKey">"key"的值</param> 
        /// <returns>返回"value"的值</returns> 
        internal static string GetConfigValue(string path, string appKey)
        {
            XmlDocument xDoc = new XmlDocument();
            XmlNode xNode;
            XmlElement xElem = null;
            try
            {
                xDoc.Load(path);

                xNode = xDoc.SelectSingleNode("//appSettings");

                xElem = (XmlElement)xNode.SelectSingleNode("//add[@key=\"" + appKey + "\"]");
            }
            catch (XmlException ex)
            {
                MeBox(ex.Message);
            }
            if (xElem != null)
                return xElem.GetAttribute("value");
            else
                return "";
        }

        /// <summary> 
        /// 设置.exe.config的值 
        /// </summary> 
        /// <param name="path">.exe.config文件的路径</param> 
        /// <param name="appKey">"key"的值</param> 
        /// <param name="appValue">"value"的值</param> 
        internal static void SetConfigValue(string path, string appKey, string appValue)
        {
            XmlDocument xDoc = new XmlDocument();
            try
            {
                xDoc.Load(path);

                XmlNode xNode;
                XmlElement xElem1;
                XmlElement xElem2;

                xNode = xDoc.SelectSingleNode("//appSettings");

                xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key=\"" + appKey + "\"]");
                if (xElem1 != null) xElem1.SetAttribute("value", appValue);
                else
                {
                    xElem2 = xDoc.CreateElement("add");
                    xElem2.SetAttribute("key", appKey);
                    xElem2.SetAttribute("value", appValue);
                    xNode.AppendChild(xElem2);
                }
                xDoc.Save(Application.StartupPath + "\\" + path);
            }
            catch (XmlException ex)
            {
                MeBox(ex.Message);
            }
        }

        /// <summary> 
        /// 判断软件的更新日期 
        /// </summary> 
        /// <param name="Dir">服务器地址</param> 
        /// <returns>返回日期</returns> 
        private static string GetTheLastUpdateTime(string Dir)
        {
            string LastUpdateTime = "";
            string AutoUpdaterFileName = Dir + "AutoUpdater/AutoUpdater.xml";
            try
            {
                WebClient wc = new WebClient();
                Stream sm = wc.OpenRead(AutoUpdaterFileName);
                XmlTextReader xml = new XmlTextReader(sm);
                while (xml.Read())
                {
                    if (xml.Name == "UpdateTime")
                    {
                        LastUpdateTime = xml.GetAttribute("Date");
                        break;
                    }
                }
                xml.Close();
                sm.Close();
            }
            catch (WebException ex)
            {
                MeBox(ex.Message);
            }
            return LastUpdateTime;
        }
    }
}

 

posted on 2015-01-05 10:42  酒歌  阅读(425)  评论(0编辑  收藏  举报