自动更新 异步调用 显示进度条 只做记录

该博客介绍了如何实现自动更新功能,包括从服务器获取版本信息,进行异步下载并显示进度条,以及后续的安装过程。在下载过程中,通过事件处理来更新进度条状态,确保用户能了解下载和安装的状态。同时,文章还涉及到文件的解压缩和版本对比,以确定是否需要更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Xml;
using System.Net;
using System.IO;
using Microsoft.Win32;
using System.Reflection;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using DevExpress.XtraEditors;

namespace DutySystem
{
    public partial class Form1 : DevExpress.XtraEditors.XtraForm
    {
        #region 窗体事件

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            VersionCheck(Application.StartupPath);
        }
        #endregion

        #region 全局变量
        byte[] IVArray ={ 57, 160, 21, 190, 162, 87, 36, 239 };
        //加密使用iv
        byte[] keyArray = { 32, 248, 65, 42, 22, 36, 63, 225, 22, 165, 157, 225, 177, 91, 243, 41, 67, 25, 39, 63, 229, 148, 163, 232 };
        //服务器更新列表暂存地址
        string ServerPath = Application.StartupPath + "//server.xml";
        //本地配置文件
        string MachineConfig = Application.StartupPath + "//MachineConfig.xml";
        //本地版本文件
        string LocalPath = Application.StartupPath + "//UpdateConfig.xml";
        //开始下载
        string Begin_DownLoad_FileName = "";
        int Begin_DownLoad_Length = 0;

        //下载中
        string DownLoading_FileName = "";
        int DownLoading_First = 0;

        //单个文件下载成功
        string Completed_DownLoad_FileName = "";

        //开始安装事件
        string Begin_Install_FileName = "";
        int Begin_Install_Length = 0;

        //单个文件安装完成
        string Completed_File_Install_FileName = "";
        #endregion

        #region 公共方法

        #region 升级版本         private void VersionCheck(string desPath)

        ///   <summary>  
        /// 从webServiceAddress中下载新版本  
        ///   </summary>  
        ///   <param   name="desPath">本地文件升级目录</param>  
        private void VersionCheck(string desPath)
        {
            //注册监听服务端口           
            try
            {

                AsynCall updateVers = new AsynCall();
                updateVers.LocalPath = LocalPath;
                updateVers.MachineConfig = MachineConfig;
                updateVers.ServerPath = ServerPath;
                //开始下载事件
                //updateVers.Begin_DownLoad += new AsynCall._Begin_DownLoad(updateVers_Begin_DownLoad);
                //下载中事件
                updateVers.DownLoading += new AsynCall._DownLoading(updateVers_DownLoading);
                //所有文件下载成功事件
                updateVers.Completed_DownLoad += new AsynCall._Completed_DownLoad(updateVers_Completed_DownLoad);
                //开始安装事件
                updateVers.Begin_Install += new AsynCall._Begin_Install(updateVers_Begin_Install);
                //单个文件安装成功事件
                updateVers.Completed_File_Install += new AsynCall._Completed_File_Install(updateVers_Completed_File_Install);
                //更新完成事件
                updateVers.RunCompleted += new AsynCall._RunCompleted(updateVers_RunCompleted);
                //代理赋值
                updateVers.ClientWebProxy = GetProxy();
                //执行更新

                //此步操作直接进行更新,不再判断版本
                Lb_InstallStatus.Text = "正在获取服务器版本请稍等......";

                string ver = updateVers.GetServerVer();
                if (ver.Length > 2)
                {
                    if (ver[0] == 'o' && ver[1] == 'k')
                    {
                        //正常格式 ok|本地版本|服务器版本|是否需要更新

                        this.Text = "当前版本:" + ver.Split('|')[1].ToString() + "  服务器版本:" + ver.Split('|')[2].ToString();
                        if (ver.Split('|')[3].ToString() == "true")
                        {
                            this.Text += "(您需要更新)";

                            //执行更新
                            updateVers.VersionUpdate(desPath);
                        }
                        else
                        {
                            this.Text += "(您不需要更新)";
                            Pb_Download.Value = 0;
                            Pb_Installer.Value = 0;
                            RunMainProcess();
                            return;
                        }
                    }
                }
                else
                {
                    MessageBox.Show("版本文件获取失败,请检查代理设置!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "升级失败,原因是:" + ex.Message);
            }
        }
   

        #region 升级相关事件

        ////开始下载
        //string Begin_DownLoad_FileName = "";
        //int Begin_DownLoad_Length = 0;

        ////下载中
        //string DownLoading_FileName = "";

        ////单个文件下载成功
        //string Completed_DownLoad_FileName = "";

        ////开始安装事件
        //string Begin_Install_FileName = "";
        //int Begin_Install_Length = 0;

        ////单个文件安装完成
        //string Completed_File_Install_FileName = "";


        //更新完成后事件
        string updateVers_RunCompleted()
        {
            string Olock = "";
            lock (Olock)
            {
                MethodInvoker mi = new MethodInvoker(updateVers_RunCompleted_Enovi);
                BeginInvoke(mi);
            }
            return "";
        }
        ////开始下载事件
        //string updateVers_Begin_DownLoad(string fileName, int length)
        //{
        //      string Olock = "";
        //      lock (Olock)
        //      {
        //          Begin_DownLoad_FileName = fileName;
        //          Begin_DownLoad_Length = length;
        //          MethodInvoker mi = new MethodInvoker(updateVers_Completed_DownLoad_Enovi);
        //          BeginInvoke(mi);
        //      }
        //    return "";
        //}
        //下载中事件
        string updateVers_DownLoading(string fileName, int isFirst, int maxLength)
        {
            string Olock = "";
            lock (Olock)
            {
                DownLoading_FileName = fileName;
                DownLoading_First = isFirst;
                Begin_DownLoad_Length = maxLength;
                MethodInvoker mi = new MethodInvoker(updateVers_DownLoading_Enovi);
                BeginInvoke(mi);
            }
            return "";
        }
        //单个文件下载成功事件
        string updateVers_Completed_DownLoad(string fileName)
        {
              string Olock = "";
              lock (Olock)
              {
                  Completed_DownLoad_FileName = fileName;
                  MethodInvoker mi = new MethodInvoker(updateVers_Completed_DownLoad_Enovi);
                  BeginInvoke(mi);
              }
            return "";
        }
        //开始安装事件
        string updateVers_Begin_Install(string fileName, int filesCount)
        {
              string Olock = "";
              lock (Olock)
              {
                  Begin_Install_FileName = fileName;
                  Begin_Install_Length = filesCount;
                  MethodInvoker mi = new MethodInvoker(updateVers_Begin_Install_Enovi);
                  BeginInvoke(mi);
              }
            return "";
        }
        //单个文件安装完成事件
        string updateVers_Completed_File_Install(string fileName)
        {
              string Olock = "";
              lock (Olock)
              {
                  Completed_File_Install_FileName = fileName;
                  MethodInvoker mi = new MethodInvoker(updateVers_Completed_File_Install_Enovi);
                  BeginInvoke(mi);
              }
            return "";
        }


        //====================================================================
        //更新完成后事件

        private void updateVers_RunCompleted_Enovi()
        {
            Lb_InstallStatus.Text = "更新已完成,正在进入系统......";
            RunMainProcess();
        }

        ////开始下载事件
        //private void updateVers_Begin_DownLoad_Enovi()
        //{
        //    Pb_Download.Maximum = Begin_DownLoad_Length;
        //    Pb_Download.Value = 0;
        //    Lb_InstallStatus.Text = "正在下载文件: " + (Begin_DownLoad_FileName.Split(Convert.ToChar(@"/")))[Begin_DownLoad_FileName.Split(Convert.ToChar(@"/")).Length - 1] ;
        //}

        //下载中事件
        private void updateVers_DownLoading_Enovi()
        {
            if (DownLoading_First == 1)
            {
                Pb_Download.Value = 0;
                textBox1.Text += "正在下载文件: " + (DownLoading_FileName.Split(Convert.ToChar(@"/")))[DownLoading_FileName.Split(Convert.ToChar(@"/")).Length - 1] + Environment.NewLine;
            }
            else
            {
                Pb_Download.Value += 1;
            }
            Pb_Download.Maximum = Begin_DownLoad_Length;
            Lb_InstallStatus.Text = "正在下载文件: " + (DownLoading_FileName.Split(Convert.ToChar(@"/")))[DownLoading_FileName.Split(Convert.ToChar(@"/")).Length - 1];
        }

        //单个文件下载成功事件
        private void updateVers_Completed_DownLoad_Enovi()
        {
            Pb_Download.Value = Pb_Download.Maximum;
            Lb_InstallStatus.Text = "文件下载成功: " + (Completed_DownLoad_FileName.Split(Convert.ToChar(@"/")))[Completed_DownLoad_FileName.Split(Convert.ToChar(@"/")).Length - 1];
            textBox1.Text += Lb_InstallStatus.Text + Environment.NewLine;
        }

        //开始安装事件
        private void updateVers_Begin_Install_Enovi()
        {
            Pb_Installer.Maximum = Begin_Install_Length;
            Lb_InstallStatus.Text = "正在安装文件: " + Begin_Install_FileName;
            textBox1.Text += Lb_InstallStatus.Text + Environment.NewLine;
        }

        //单个文件安装完成事件
        private void updateVers_Completed_File_Install_Enovi()
        {
            Pb_Installer.Value += 1;
            Lb_InstallStatus.Text = "文件安装完成: " + Completed_File_Install_FileName;
            textBox1.Text += Lb_InstallStatus.Text + Environment.NewLine;
        }


        #endregion
        #endregion

        #region 加密与解密       EncryptString(...)  DecryptTextFromMemory(...)


        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="plainTextArray">需要加密的明文</param>
        /// <param name="Key">key</param>
        /// <param name="IV">iv</param>
        /// <returns></returns>
        public static string EncryptString(string plainTextString, byte[] Key, byte[] IV)
        {
            try
            {
                // 使用utf-8编码(也可以使用其它的编码)
                Encoding sEncoding = Encoding.GetEncoding("utf-8");
                // 把字符串明文转换成utf-8编码的字节流
                byte[] plainTextArray = sEncoding.GetBytes(plainTextString);

                // 建立一个MemoryStream,这里面存放加密后的数据流
                MemoryStream mStream = new MemoryStream();
                // 使用MemoryStream 和key、IV新建一个CryptoStream 对象
                CryptoStream cStream = new CryptoStream(mStream,
                    new TripleDESCryptoServiceProvider().CreateEncryptor(Key, IV),
                    CryptoStreamMode.Write);
                // 将加密后的字节流写入到MemoryStream
                cStream.Write(plainTextArray, 0, plainTextArray.Length);
                //把缓冲区中的最后状态更新到MemoryStream,并清除cStream的缓存区
                cStream.FlushFinalBlock();
                // 把解密后的数据流转成字节流
                byte[] ret = mStream.ToArray();
                // 关闭两个streams.
                cStream.Close();
                mStream.Close();

                string str = "";
                foreach (byte var in ret)
                {
                    str += var + "#";
                }

                return str;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return "";
            }
        }


        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="EncryptedDataArray">需要解密的密文字节流</param>
        /// <param name="Key">key</param>
        /// <param name="IV">iv</param>
        /// <returns></returns>
        public static string DecryptTextFromMemory(string EncryptedDataString, byte[] Key, byte[] IV)
        {
            try
            {

                //string 转换为 bytes
                Encoding sEncoding = Encoding.GetEncoding("utf-8");
                string[] str_Arry = EncryptedDataString.Split('#');
                byte[] EncryptedDataArray = new byte[str_Arry.Length - 1];

                for (int i = 0; i < str_Arry.Length - 1; i++)
                {
                    EncryptedDataArray[i] = Convert.ToByte(int.Parse(str_Arry[i]));
                }


                // 建立一个MemoryStream,这里面存放加密后的数据流
                MemoryStream msDecrypt = new MemoryStream(EncryptedDataArray);
                // 使用MemoryStream 和key、IV新建一个CryptoStream 对象
                CryptoStream csDecrypt = new CryptoStream(msDecrypt,
                    new TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV),
                    CryptoStreamMode.Read);
                // 根据密文byte[]的长度(可能比加密前的明文长),新建一个存放解密后明文的byte[]
                byte[] DecryptDataArray = new byte[EncryptedDataArray.Length];
                // 把解密后的数据读入到DecryptDataArray
                csDecrypt.Read(DecryptDataArray, 0, DecryptDataArray.Length);
                msDecrypt.Close();
                csDecrypt.Close();
                return sEncoding.GetString(DecryptDataArray);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return "";
            }

        }

        #endregion

        #region 得到代理         private WebProxy GetProxy()

        /// <summary>
        /// 获得本地代理
        /// </summary>
        /// <returns></returns>
        private WebProxy GetProxy()
        {
            XmlDocument xd = new XmlDocument();
            xd.Load(MachineConfig);

            bool isProxy = false;
            string serverIp = "";
            string serverPort = "";
            string userName = "";
            string userPwd = "";

            foreach (XmlNode var in xd.ChildNodes[0])
            {
                switch (var.Name)
                {
                    case "IsProxy":
                        if (var.InnerText.Trim() == "true")
                        {
                            isProxy = true;
                        }
                        break;
                    case "ServerIP":
                        serverIp = var.InnerText.Trim();
                        break;
                    case "ServerPort":
                        serverPort = var.InnerText.Trim();
                        break;
                    case "ServerUSE":
                        userName = var.InnerText.Trim();
                        break;
                    case "ServerPWD":
                        userPwd = var.InnerText.Trim();
                        break;
                    default:
                        break;
                }
            }

            if (isProxy)
            {//如果下载的网址支持代理
                WebProxy wp = new WebProxy(serverIp, int.Parse(serverPort));
                wp.BypassProxyOnLocal = false;
                ICredentials credentials = new NetworkCredential(userName, DecryptTextFromMemory(userPwd,keyArray,IVArray));
                wp.Credentials = credentials;
                return wp;
            }
            else
            {//如果下载的网址不支持代理
                return null;
            }
        }
        #endregion

        #region 运行主程序       private void RunMainProcess()

        private void RunMainProcess()
        {
            //System.Threading.Thread.Sleep(2);
            XmlDocument xd = new XmlDocument();
            if (!File.Exists(MachineConfig))
            {
                return;
            }
            else
            {
                try
                {
                    System.Diagnostics.Process Process1 = new System.Diagnostics.Process();

                    xd.Load(MachineConfig);
                    foreach (XmlNode var in xd.ChildNodes[0])
                    {
                        if (var.Name == "ExePro")
                        {
                            Process1.StartInfo.FileName = var.InnerText.Trim();
                        }
                    }
                    Process1.StartInfo.CreateNoWindow = true;
                    Process1.Start();

                    //do { } while (!Process1.HasExited);
                    this.Close();
                }
                catch (System.Exception ex)
                {
                    string a = ex.Message;
                }
            }

 

        }
        #endregion             
       
        #endregion

    }

    #region 更新核心类

    class AsynCall
    {
        #region 委托 事件定义

        //更新版本 异步调用单个文件的更新
        public delegate string _UpdateVer(string path);
        //委托 开始下载单个文件
        public delegate string _Begin_DownLoad(string fileName, int length);
        //委托 下载中
        public delegate string _DownLoading(string fileName, int isFirst, int maxLength);
        //委托 完成单个文件的下载
        public delegate string _Completed_DownLoad(string fileName);
        //委托 开始安装所有文件
        public delegate string _Begin_Install(string fileName, int filesCount);
        //委托 完成单个文件的安装
        public delegate string _Completed_File_Install(string fileName);
        //委托 完成所有文件的安装
        public delegate string _RunCompleted();


        //事件 开始下载
        public event _Begin_DownLoad Begin_DownLoad;
        //事件 下载中
        public event _DownLoading DownLoading;
        //事件 完成单个文件的下载
        public event _Completed_DownLoad Completed_DownLoad;
        //委托 开始安装单个文件
        public event _Begin_Install Begin_Install;
        //事件 完成单个文件的安装
        public event _Completed_File_Install Completed_File_Install;
        //时间 完成所有文件安装
        public event _RunCompleted RunCompleted;

        #endregion

        #region 属性方法

        //服务器更新列表暂存地址
        string _ServerPath = "";
        //本地配置文件
        string _MachineConfig = "";
        //本地版本文件
        string _LocalPath = "";
        //要更新文件总数
        int _UpdateFiles;
        //当前客户端代理
        WebProxy _ClientWebProxy = null;

        //服务器更新列表暂存地址
        public string ServerPath
        {
            get
            {
                return _ServerPath;
            }
            set
            {
                _ServerPath = value;
            }
        }

        //本地配置文件
        public string MachineConfig
        {
            get
            {
                return _MachineConfig;
            }
            set
            {
                _MachineConfig = value;
            }
        }

        //本地版本文件
        public string LocalPath
        {
            get
            {
                return _LocalPath;
            }
            set
            {
                _LocalPath = value;
            }
        }

        //要更新文件总数
        public int UpdateFiles
        {
            get
            {
                return _UpdateFiles;
            }
        }

        //当前客户端代理
        public WebProxy ClientWebProxy
        {
            set
            {
                _ClientWebProxy = value;
            }
        }
        #endregion

        #region 公共方法

        #region 升级版本         private void VersionCheck(string desPath)

        ///   <summary>  
        /// 从webServiceAddress中下载新版本  
        ///   </summary>  
        ///   <param   name="desPath">本地文件升级目录</param>  
        public void VersionUpdate(string desPath)
        {
            _UpdateVer uv = new _UpdateVer(UpdateVer);
            AsyncCallback ac = new AsyncCallback(CallBackFun);
            IAsyncResult ia = uv.BeginInvoke(desPath, ac, uv);           
        }

        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="ar"></param>
        public void CallBackFun(IAsyncResult ar)
        {
            try
            {
                _UpdateVer dlgt = (_UpdateVer)ar.AsyncState;

                object o = dlgt.EndInvoke(ar);
                if (o != null)
                {
                    RunCompleted();
                }
            }
            catch (Exception ex)
            {
                return;
            }
        }

        /// <summary>
        /// 更新文件异步调用函数
        /// </summary>
        /// <param name="desPath"></param>
        /// <returns></returns>
        public string UpdateVer(string desPath)
        {
            //注册监听服务端口           
            try
            {
                #region   查看文件和目录

                //取得服务器更新版本文件               
                System.Xml.XmlDocument serverXmlDoc = new System.Xml.XmlDocument();
                serverXmlDoc.Load(ServerPath);

                //判断文件版本
                if (!desPath.EndsWith(@"/"))
                    desPath += @"/";

                if (!System.IO.Directory.Exists(desPath))
                {
                    System.IO.Directory.CreateDirectory(desPath);
                }

                string tempPath = desPath + @"tempDesPathCache/";

                if (System.IO.Directory.Exists(tempPath))
                {
                    System.IO.Directory.Delete(tempPath, true);
                    System.IO.Directory.CreateDirectory(tempPath);
                }
                else
                    System.IO.Directory.CreateDirectory(tempPath);

                if (!System.IO.File.Exists(desPath + "UpdateConfig.xml"))
                {
                    System.Xml.XmlDocument updateConfig = new System.Xml.XmlDocument();
                    updateConfig.LoadXml(@"<root></root>");
                    updateConfig.Save(desPath + "UpdateConfig.xml");
                }
                #endregion

                #region 升级

                System.Xml.XmlDocument localXmlDoc = new System.Xml.XmlDocument();
                localXmlDoc.Load(desPath + "UpdateConfig.xml");
                bool newVersionExist = false;
                bool moduleExist = false;
                System.Xml.XmlNode serverNode0 = serverXmlDoc.ChildNodes[0];
                System.Xml.XmlNode localNode0 = localXmlDoc.ChildNodes[0];
                foreach (System.Xml.XmlNode serverNode in serverNode0)
                {
                    if (serverNode.Name == "vertion")
                    {//如果是程序版本号则跳过此次检验
                        continue;
                    }
                    moduleExist = false;
                    foreach (System.Xml.XmlNode localNode in localNode0)
                    {
                        //找到对应模块  
                        if (localNode.ChildNodes[0].InnerText == serverNode.ChildNodes[0].InnerText)
                        {
                            moduleExist = true;
                            newVersionExist = true;
                            //版本号判断  
                            if (localNode.ChildNodes[1].InnerText.CompareTo(serverNode.ChildNodes[1].InnerText) < 0)
                            {                                 
                                DownloadFile(serverNode.ChildNodes[2].InnerText, tempPath + serverNode.ChildNodes[0].InnerText);
                            }
                            break;
                        }
                    }
                    //没找到对应模块  
                    if (false == moduleExist)
                    {
                        newVersionExist = true;
                        DownloadFile(serverNode.ChildNodes[2].InnerText, tempPath + serverNode.ChildNodes[0].InnerText);
                    }
                }

                //写入新UpdateConfig.xml升级完毕后替换  
                if (newVersionExist)
                {
                    serverXmlDoc.Save(tempPath + "UpdateConfig.xml");

                    string[] dirs = System.IO.Directory.GetFiles(tempPath, "*.*");
                    string fileName;
                    //////////////////////////////////////
                    /////执行开始安装事件
                    Begin_Install(((dirs[0].Split(Convert.ToChar(@"/")))[dirs[0].Split(Convert.ToChar(@"/")).Length - 1]), dirs.Length);
                    //////////////////////////////////////
                    foreach (string dir in dirs)
                    {
                        fileName = ((dir.Split(Convert.ToChar(@"/")))[dir.Split(Convert.ToChar(@"/")).Length - 1]);
                        //////////////////////////////////////
                        /////执行单个文件安装完成
                        Completed_File_Install(fileName);
                        //////////////////////////////////////

                        if (fileName.LastIndexOf('.') != -1)
                        {
                            if (fileName.Split('.')[fileName.Split('.').Length - 1].ToString().ToUpper() == "RAR")
                            { //如果是rar文件则解压缩
                                unRAR(desPath, dir);
                                //直接执行下一个循环
                                continue;
                            }
                        }

                        //如果不是rar文件则执行普通操作
                        if (System.IO.File.Exists(desPath + fileName))
                        {
                            System.IO.File.Delete(desPath + fileName);
                        }
                        System.IO.File.Move(dir, desPath + fileName);
                    }                   
                }

                #endregion
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                File.Delete(Application.StartupPath + "//server.xml");
            }
            return "安装完成";
        }
        #endregion

        #region 下载文件         private void DownloadFile(string source, string fileName)

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="source">文件地址</param>
        /// <param name="fileName">文件保存地址</param>
        private void DownloadFile(string source, string fileName)
        {
            try
            {
                //WebProxy _WP = new WebProxy(ProxyName, ProxyPort);
                FileStream localStream;
                //create   a   web   Httprequest    
                HttpWebRequest wReq = (HttpWebRequest)HttpWebRequest.Create(source);
                //set   the   address   and   port   of   the   proxy   server    

                WebProxy wp = _ClientWebProxy;
                if (wp != null)
                {
                    wReq.Proxy = wp;
                }
                //set   the   web   request's   proxy   server               
                //create   a   web   Httpresponse    
                HttpWebResponse wResp = (HttpWebResponse)wReq.GetResponse();
                //write   the   response   to   a   stream    
                Stream respStream = wResp.GetResponseStream();
                //create   a   new   file   to   receive   the   response   stream    
                localStream = new FileStream(fileName, FileMode.Append, FileAccess.Write);

                //////////////////////////////////////////////
                /////////激活开始下载事件
                int tick = 1;
                int count = 0;
                int current = 1;
                //是否第一次执行下载
                int isFirst = 1;
                //开始下载事件触发
                if (wResp.ContentLength / 1280 * 1280 < localStream.Length)
                {
                   
                    count = (int)(wResp.ContentLength / (long)1280) + 1;
                }
                else
                {
                    count = (int)(wResp.ContentLength / (long)1280);
                }
                if (count > 10)
                {
                    tick = count / 10;
                }
                //Begin_DownLoad(fileName, 10);
                //////////////////////////////////////////////               

                BinaryReader reader = new BinaryReader(respStream);

                //set   the   receive   binary   buffer    
                const int BufferSize = 102400;
                byte[] buffer = new Byte[BufferSize];
                bool bFinished = false;
                int dataRead;

                //just   write   the   buffer   to   the   binaryReader   again   and   again    
                do
                {
                    try
                    {
                        dataRead = reader.Read(buffer, 0, BufferSize);
                        if (dataRead == 0)
                        {
                            bFinished = true;
                            //////////////////////////////////////////////
                            /////////激活下载完成事件
                            Completed_DownLoad(fileName);
                            //////////////////////////////////////////////

                        }
                        else
                        {
                            //////////////////////////////////////////////
                            ////激活下载事件
                            ++current;
                            if (isFirst == 1)
                            {
                                DownLoading(fileName, isFirst,10);
                                isFirst = 0;
                            }

                            if (current == tick)
                            {
                                current = 0;
                                DownLoading(fileName, isFirst,10);
                            }
                            /////////////////////////////////////////////
                        }
                        localStream.Write(buffer, 0, dataRead);
                    }
                    catch
                    {
                        localStream.Close();
                        respStream.Close();
                    }
                } while (!bFinished);
                //close   all   file   stream    
                localStream.Close();
                respStream.Close();
                //ShowLog("Download   finished");
            }
            catch (Exception ex)
            {
                throw new Exception("下载失败,原因是:" + ex.Message, ex);
            }
        }

        #endregion

        #region 解压缩文件       private void unRAR(string unRarPatch, string rarPatch)

        /// <summary>
        /// 解压缩rar文件
        /// </summary>
        private void unRAR(string unRarPatch, string rarPatch)
        {
            string OLock = "";
            lock (OLock)
            {
                try
                {
                    string strzipPath = rarPatch;
                    System.Diagnostics.Process Process1 = new System.Diagnostics.Process();
                    Process1.StartInfo.FileName = "WinRAR.exe";
                    Process1.StartInfo.CreateNoWindow = true;
                    Process1.StartInfo.Arguments = " x -o+ " + strzipPath + " " + unRarPatch;
                    Process1.Start();
                    //MessageBox.Show(Process1.HasExited.ToString());

                    do { } while (!Process1.HasExited);
               
                    if (Process1.HasExited)
                    {
                        int iExitCode = Process1.ExitCode;
                    }
                }
                catch (System.Exception)
                {
                }
            }

            #region 其他命令格式
            //// 1
            ////压缩c:/freezip/free.txt(即文件夹及其下文件freezip/free.txt)
            ////到c:/freezip/free.rar
            //strzipPath = "C://freezip//free";//默认压缩方式为 .rar
            //Process1.StartInfo.Arguments = " a -r " + strzipPath + " " + strtxtPath;

            //// 2
            ////压缩c:/freezip/free.txt(即文件夹及其下文件freezip/free.txt)
            ////到c:/freezip/free.rar
            //strzipPath = "C://freezip//free";//设置压缩方式为 .zip
            //Process1.StartInfo.Arguments = " a -afzip " + strzipPath + " " + strtxtPath;

            //// 3
            ////压缩c:/freezip/free.txt(即文件夹及其下文件freezip/free.txt)
            ////到c:/freezip/free.zip  直接设定为free.zip
            //Process1.StartInfo.Arguments = " a -r "+strzipPath+" " + strtxtPath ;

            //// 4
            ////搬迁压缩c:/freezip/free.txt(即文件夹及其下文件freezip/free.txt)
            ////到c:/freezip/free.rar 压缩后 原文件将不存在
            //Process1.StartInfo.Arguments = " m " + strzipPath + " " + strtxtPath;

            //// 5
            ////压缩c:/freezip/下的free.txt(即文件free.txt)
            ////到c:/freezip/free.zip  直接设定为free.zip 只有文件 而没有文件夹
            //Process1.StartInfo.Arguments = " a -ep " + strzipPath + " " + strtxtPath;

            //// 6
            ////解压缩c:/freezip/free.rar
            ////到 c:/freezip/
            //strtxtPath = "c://freezip//";
            //Process1.StartInfo.Arguments = " x " + strzipPath + " " + strtxtPath;

            //// 7
            ////加密压缩c:/freezip/free.txt(即文件夹及其下文件freezip/free.txt)
            ////到c:/freezip/free.zip  密码为123456 注意参数间不要空格
            //Process1.StartInfo.Arguments = " a -p123456 " + strzipPath + " " + strtxtPath;

            //// 8
            ////解压缩加密的c:/freezip/free.rar
            ////到 c:/freezip/   密码为123456 注意参数间不要空格
            //strtxtPath = "c://freezip//";
            //Process1.StartInfo.Arguments = " x -p123456 " + strzipPath + " " + strtxtPath;


            //// 9
            ////-o+ 覆盖 已经存在的文件
            //// -o- 不覆盖 已经存在的文件
            //strtxtPath = "c://freezip//";
            //Process1.StartInfo.Arguments = " x -o+ " + strzipPath + " " + strtxtPath;

            ////10
            //// 只从指定的zip中
            //// 解压出free1.txt
            //// 到指定路径下
            //// 压缩包中的其他文件 不予解压
            //strtxtPath = "c://freezip//";
            //Process1.StartInfo.Arguments = " x " + strzipPath + " " +" free1.txt" + " " + strtxtPath;

            //// 11
            //// 通过 -y 对所有询问回应为"是" 以便 即便发生错误 也不弹出WINRAR的窗口
            //// -cl 转换文件名为小写字母
            //strtxtPath = "c://freezip//";
            //Process1.StartInfo.Arguments = " t -y -cl " + strzipPath + " " + " free1.txt";
            #endregion
        }


        #endregion

        #region 获取服务器版本文件         public string GetServerVer(ref string localVer,ref string serverVer,ref bool isUpdate)

        /// <summary>
        /// 获取服务器版本文件
        /// </summary>
        /// <param name="localVer">本地版本</param>
        /// <param name="serverVer">服务器版本</param>
        /// <param name="isUpdate">是否更新 true:更新</param>
        public string GetServerVer()
        {
            try
            {
                string result = "ok|";
                XmlDocument xd = new XmlDocument();
                xd.Load(MachineConfig);
                foreach (XmlNode var in xd.ChildNodes[0])
                {
                    if (var.Name == "ServerUpXML")
                    {
                        if (File.Exists(ServerPath))
                        {
                            File.Delete(ServerPath);
                        }
                        DownloadFile(var.InnerText.Trim(), ServerPath);
                    }
                }

                //服务器版本
                string serverVer = GetUpListVer(ServerPath);
                //本地版本
                string localVer = GetUpListVer(LocalPath);
                //是否更新
                bool isUpdate = false;
                if (localVer.CompareTo(serverVer) < 0)
                {//需要更新
                    isUpdate = true;
                }
                else
                {
                    isUpdate = false;
                }

                //正常格式 ok|本地版本|服务器版本|是否需要更新
                result = result + localVer + "|" + serverVer + "|" + (isUpdate == true ? "true" : "false");

                return result;

            }
            catch (System.Exception ex)
            {
                return ex.Message;
            }

        }

        /// <summary>
        ///  获取文件版本号
        /// </summary>
        /// <param name="_VerPath">版本号文件</param>
        /// <returns></returns>
        private string GetUpListVer(string _VerPath)
        {
            XmlDocument xd = new XmlDocument();
            if (File.Exists(_VerPath))
            {
                try
                {
                    xd.Load(_VerPath);
                    return xd.ChildNodes[0].ChildNodes[0].InnerText.Trim();
                }
                catch (System.Exception ex)
                {
                    return "0.0";
                }
            }
            else
            {
                return "0.0";
            }
        }
        #endregion

        #endregion
    }
    #endregion
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值