自动更新

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;

namespace UpdateClient
{
    public partial class UpdateClient : Form
    {

        public UpdateClient()
        {
            InitializeComponent();
        }

        #region 窗体事件

        #region 窗体初始化         private void UpdateClient_Load(object sender, EventArgs e)

        /// <summary>
        /// 窗体初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateClient_Load(object sender, EventArgs e)
        {
            //初始化界面设置
            ServerProxy(false);
            //获得服务器版本文件
            GetServerUpList();

            //判断当前的版本号
            string _Client_Ver = GetUpListVer(VerConfig);
            string _Server_Ver = GetUpListVer(ServerPath);
            IsUpdate = _Client_Ver.CompareTo(_Server_Ver);

            if (IsUpdate < 0 )
            {
                this.Text = "当前版本:" + _Client_Ver + " 服务器版本是:" + _Server_Ver + " (需要更新)";
            }
            else
            {
                this.Text = "当前版本:" + _Client_Ver + " 服务器版本是:" + _Server_Ver + " (不需要更新)";
                Btn_ShowMsg.Enabled = false;
                Btn_UpDate.Text = "进入系统";
            }
        }
        #endregion

        #region 其他事件 [代理选择] [显示详细] [保存当前代理设置 升级]

            /// <summary>
            /// 是否支持代理
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void checkBox1_CheckedChanged(object sender, EventArgs e)
            {
                Txt_ServerIP.Enabled = checkBox1.Checked;
                Txt_ServerPort.Enabled = checkBox1.Checked;
                Txt_ServerPWD.Enabled = checkBox1.Checked;
                Txt_ServerUSE.Enabled = checkBox1.Checked;
            }

            /// <summary>
            /// 是否显示详细信息
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void Btn_ShowMsg_Click(object sender, EventArgs e)
            {
                if (IsShowMsg)
                {
                    IsShowMsg = false;
                    this.MaximumSize = new Size(328, 235);
                    this.MinimumSize = new Size(328, 235);
                }
                else
                {
                    IsShowMsg = true;
                    this.MaximumSize = new Size(328, 400);
                    this.MinimumSize = new Size(328, 400);
                }
            }

            /// <summary>
            /// 升级并保存当前设置
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void Btn_UpDate_Click(object sender, EventArgs e)
            {
                if (IsUpdate < 0)
                {
                    //代理设置
                    ServerProxy(true);
                    //下载服务器最新版本文件
                    GetServerUpList();
                    //更新服务器版本
                    VersionCheck(Application.StartupPath);

                    if (MessageBox.Show(this, "更新完毕,是否重新启动程序", "升级完毕", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        //启动主程序
                        RunMainProcess();
                    }
                    else
                    {
                        //this.Close();
                    }
                }
                else
                {
                    RunMainProcess();
                }
            }
            #endregion
        #endregion

        #region 全局变量

        bool IsShowMsg = false;

        //每次启动需要判断 key iv 是否为空,如果为空则需要重新给代理赋值
        //加密使用key
        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 VerConfig = Application.StartupPath + "//UpdateConfig.xml";
        //是否需要更新
        int IsUpdate = -1;
        /// <summary>
        /// 临时信息
        /// </summary>
        string Msg = "";

        int UpFileCount = 0;
        #endregion

        #region 公共方法

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

        ///   <summary>  
        /// 从webServiceAddress中下载新版本  
        ///   </summary>  
        ///   <param   name="desPath">本地文件升级目录</param>  
        private void VersionCheck(string desPath)
        {
            //注册监听服务端口           
            try
            {
                #region   查看文件和目录
                PB_.Maximum = 0;
                AsynCall ac = new AsynCall();
                ac.RunCompleted += new AsynCall._RunCompleted(ac_RunCompleted);

                //取得服务器更新版本文件               
                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 升级

                UpFileCount = 0;
                PB_.Value = 0;
                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;
                            //版本号判断  
                            if (localNode.ChildNodes[1].InnerText.CompareTo(serverNode.ChildNodes[1].InnerText) < 0)
                            {
                                UpFileCount += 1;
                                newVersionExist = true;
                                DownloadFile(serverNode.ChildNodes[2].InnerText, tempPath + serverNode.ChildNodes[0].InnerText);

                                //异步显示文件进度
                                ac.UpdateVers("----正在下载文件:" + serverNode.ChildNodes[0].InnerText);
                            }
                            break;
                        }
                    }
                    //没找到对应模块  
                    if (false == moduleExist)
                    {
                        UpFileCount += 1;
                        newVersionExist = true;
                        DownloadFile(serverNode.ChildNodes[2].InnerText, tempPath + serverNode.ChildNodes[0].InnerText);
                        ac.UpdateVers("----正在下载文件:" + serverNode.ChildNodes[0].InnerText);
                    }
                }

                PB_.Maximum = UpFileCount * 2 + 1;
                //写入新UpdateConfig.xml升级完毕后替换  
                if (newVersionExist)
                {
                    serverXmlDoc.Save(tempPath + "UpdateConfig.xml");

                    string[] dirs = System.IO.Directory.GetFiles(tempPath, "*.*");
                    string fileName;

                    foreach (string dir in dirs)
                    {
                        fileName = ((dir.Split(Convert.ToChar(@"/")))[dir.Split(Convert.ToChar(@"/")).Length - 1]);

                        if (fileName.LastIndexOf('.') != -1)
                        {
                            if (fileName.Split('.')[fileName.Split('.').Length - 1].ToString().ToUpper() == "RAR")
                            { //如果是rar文件则解压缩
                                ac.UpdateVers("----正在安装文件:" + fileName);
                                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);
                        ac.UpdateVers("----正在安装文件:" + fileName);
                    }

                    MessageBox.Show("升级完毕");
                }

                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "升级失败,原因是:" + ex.Message);
                RunMainProcess();
            }
            finally
            {
                File.Delete(Application.StartupPath + "//server.xml");
            }
        }

        /// <summary>
        /// 如果执行成功
        /// </summary>
        /// <param name="_ShowMsg"></param>
        /// <returns></returns>
        string ac_RunCompleted(string _ShowMsg)
        {
            MethodInvoker mi = new MethodInvoker(SetProcess);
            Msg = Msg + "/n" + _ShowMsg;
            BeginInvoke(mi);
            return "";
        }

        private void SetProcess()
        {
            RefFileListControl(Msg);
            Msg = "";
            PB_.Value += 1;
        }

                #endregion

        #region 获取程序版本         private string GetUpListVer(string _VerPath)

        /// <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
                {
                    return "0.0";
                }
            }
            else
            {
                return "0.0";
            }
        }
        #endregion

        #region 获取服务器版本文件         private void GetServerUpList()

        /// <summary>
        ///  获取服务器版本文件
        /// </summary>
        /// <returns></returns>
        private void GetServerUpList()
        {
            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);
                    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 = GetProxy();
                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);

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

        /// <summary>
        /// 获得本地代理
        /// </summary>
        /// <returns></returns>
        private WebProxy GetProxy()
        {
            if (checkBox1.Checked)
            {//如果下载的网址支持代理
                WebProxy wp = new WebProxy(Txt_ServerIP.Text.Trim(), int.Parse(Txt_ServerPort.Text.Trim()));
                wp.BypassProxyOnLocal = false;
                ICredentials credentials = new NetworkCredential(Txt_ServerUSE.Text.Trim(), Txt_ServerPWD.Text.Trim());
                wp.Credentials = credentials;
                return wp;
            }
            else
            {//如果下载的网址不支持代理
                return null;
            }
        }

        #region 下载测试
        //private void download()
        //{
        //    //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 = new WebProxy("192.168.11.8", 8080);


        //    wp.BypassProxyOnLocal = true;
        //    ICredentials credentials = new NetworkCredential("sun", "sun");
        //    wp.Credentials = credentials;

        //    //set   the   web   request's   proxy   server               
        //    wReq.Proxy = wp;
        //    //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);

        //    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;
        //            localStream.Write(buffer, 0, dataRead);
        //        }
        //        catch
        //        {
        //            localStream.Close();
        //            respStream.Close();
        //        }
        //    } while (!bFinished);
        //    //close   all   file   stream    
        //    localStream.Close();
        //    respStream.Close();
        //    //ShowLog("Download   finished");

        //}
        #endregion

        #endregion

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

        private void RunMainProcess()
        {

                //System.Diagnostics.Process Process1 = new System.Diagnostics.Process();
                //Process1.StartInfo.FileName = "Server.exe";
                //Process1.StartInfo.CreateNoWindow = true;
                //Process1.Start();

                //this.Close();

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

                    this.Close();
                }
                catch (System.Exception ex)
                {
                    string a = ex.Message;
                }
            }         
        
        }
        #endregion             

        #region 代理设置         public bool ServerProxy(bool _IsSave)

        /// <summary>
        /// 代理设置
        /// </summary>
        /// <param name="_IsSave">是否保存 true:保存</param>
        /// <returns></returns>
        public bool ServerProxy(bool _IsSave)
        {
            try
            {
                string _XmlPath = MachineConfig;

                if (File.Exists(_XmlPath))
                {
                    System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
                    xd.Load(_XmlPath);

                    System.Xml.XmlNode xn = xd.ChildNodes[0];

                    foreach (System.Xml.XmlNode var in xn.ChildNodes)
                    {
                        if (var.Name.Trim().Equals("IsProxy"))
                        {
                            if (_IsSave)
                            {
                                var.InnerText = checkBox1.Checked.ToString();
                            }
                            else
                            {
                                checkBox1.Checked = var.InnerText.Trim().Equals("") ? false : Convert.ToBoolean(var.InnerText.Trim());
                            }
                        }
                        if (var.Name.Trim().Equals("ServerIP"))
                        {
                            if (_IsSave)
                            {
                                var.InnerText = Txt_ServerIP.Text.Trim();
                            }
                            else
                            {
                                Txt_ServerIP.Text = var.InnerText.Trim();
                            }
                        }
                        if (var.Name.Trim().Equals("ServerPort"))
                        {
                            if (_IsSave)
                            {

                                var.InnerText = Txt_ServerPort.Text.Trim();
                            }
                            else
                            {
                                Txt_ServerPort.Text = var.InnerText.Trim();
                            }
                        }
                        if (var.Name.Trim().Equals("ServerUSE"))
                        {
                            if (_IsSave)
                            {
                                var.InnerText = Txt_ServerUSE.Text.Trim();
                            }
                            else
                            {
                                Txt_ServerUSE.Text = var.InnerText.Trim();
                            }
                        }
                        if (var.Name.Trim().Equals("ServerPWD"))
                        {
                            if (_IsSave)
                            {
                                var.InnerText = EncryptString(Txt_ServerPWD.Text.Trim(), keyArray, IVArray);
                            }
                            else
                            {
                                Txt_ServerPWD.Text = DecryptTextFromMemory(var.InnerText.Trim(), keyArray, IVArray);
                            }
                        }
                    }
                    if (_IsSave)
                    {
                        xd.Save(_XmlPath);
                    }
                }

                return true;
            }
            catch { return false; }
        }
        #endregion

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

        /// <summary>
        /// 解压缩rar文件
        /// </summary>
        public void unRAR(string unRarPatch, string rarPatch)
        {
            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();

                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 加密与解密       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 void RefFileListControl(string _FileOperator)

        /// <summary>
        /// 更新文件列表详细
        /// </summary>
        /// <param name="_FileOperator">操作说明</param>
        private void RefFileListControl(string _FileOperator)
        {
            textBox1.Text += _FileOperator + "/n";
        }
        #endregion

        #endregion
    }

    #region 异步调用类    public class AsynCall

    public class AsynCall
    {
        //如果成功 _ShowMsg :要显示的信息
        public delegate string _RunCompleted(string _ShowMsg);

        //更新版本  _ShowMsg :要显示的信息
        public delegate string _UpdateVer(string _ShowMsg);

        public event _RunCompleted RunCompleted;

        /// <summary>
        /// 更新文件 总函数
        /// </summary>
        public void UpdateVers(string _ShowMsg)
        {
            _UpdateVer uv = new _UpdateVer(UpdateVer);
            AsyncCallback asc = new AsyncCallback(CallBack);
            IAsyncResult ar = uv.BeginInvoke(_ShowMsg, asc, uv);
        }

        /// <summary>
        /// 上传文件函数
        /// </summary>
        /// <param name="_ShowMsg"></param>
        /// <returns></returns>
        public string UpdateVer(string _ShowMsg)
        {
            return _ShowMsg;
        }


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

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

 

 

 

 

 

 

//本地msconfig配置

 

 

<root>
  <ServerUpXML>http://192.168.12.6/appUpdate/UpdateConfig.xml</ServerUpXML>
  <IsProxy>True</IsProxy>
  <ServerIP>192.168.11.8</ServerIP>
  <ServerPort>8080</ServerPort>
  <ServerUSE>sun</ServerUSE>
  <ServerPWD>95#151#28#216#52#44#200#131#</ServerPWD>
  <ExePro>Client.exe</ExePro>
</root>

 

 

//服务段msconfig配置

<root>
<vertion>
  1.0
</vertion>
  <module>
    <moduleName>Client.rar</moduleName>
    <vertion>1.0.1.9</vertion>
    <appUrl>http://192.168.12.6/appUpdate/Client.rar</appUrl>
  </module>
</root>

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值