zoukankan      html  css  js  c++  java
  • C# 自动升级

    自动更新的软件的目的在于让客户不在为了寻找最新软件花费时间。也不用去到开发商的网站上查找。客户端的软件自动会在程序启动前查找服务器上最新的版本。和自己当前软件的版本比较,如果服务器的是最新版本。客户端则进行自动下载、解压、安装。当然了下载是要有网络的,并且用户可以根据提示去完成操作。再也不用为找不到最新版本的软件而头疼。下面是我的大体思路,已经得到了实现:

    1、  写一个webservice,提供一个获取服务器xml中版本的数据的方法。|
    <?xml version="1.0" encoding="utf-8" ?>
    <Content>
      <Project id="程序名称" Edition="1.0"> </Project>
    </Content>

    2、  WinForm应用程序启动的时候,首先访问webservice获取服务器的xml中的版本号,然后获取客户端的xml中的版本号。将两个版本号比较,若服务器中的版本号大,则提示提示可以在线更新应用程序。

    3、  然后客户端自动下载网络上的zip压缩包到本机的指定位置,进行自动解压缩到安装的目录进行覆盖。解压缩完毕之后,用进程打开所解压过的exe文件进行软件安装。同时关闭客户端软件所在的进程。

    4、注意:升级程序和应用程序都是单独的,应用程序在使用时不能对本身进行升级(覆盖会失败)。

    具体代码如下:

    第一部分 应用程序如口Program:

    using System;
    using System.Collections.Generic;
    using System.Windows.Forms;
    using Medicine_ERP;
    using DevExpress.XtraEditors;
    using System.Xml;
    using Anshield_AutoFutures.BaseClase;

    namespace Anshield_AutoFutures
    {
        static class Program
        {
            private static void LoadMath()
            {
                //服务器上的版本号
                string NewEdition = "1.0";
                //应用程序中的版本号
                string OldEdition = "1.0";

                try
                {
                    //服务器上的版本号
                    NewEdition = webserverClase.getCopyRightCode();

                    //获取系统中xml里面存储的版本号              
                    String fileName = Application.StartupPath + "\XMLEdition.xml";
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(fileName);
                    XmlNode xn = xmlDoc.SelectSingleNode("Content");
                    XmlNodeList xnl = xn.ChildNodes;
                    foreach (XmlNode xnf in xnl)
                    {
                        XmlElement xe = (XmlElement)xnf;
                        if (xe.GetAttribute("id") == "jigou_plz")
                        {
                            OldEdition = xe.GetAttribute("Edition");//动态数组
                        }
                        break;
                    }
                    double newE = double.Parse(NewEdition);
                    double oldE = double.Parse(OldEdition);
                    //比较两个版本号,判断应用程序是否要更新
                    if (newE > oldE)
                    {
                        //更新程序¨
                        DialogResult dr = XtraMessageBox.Show("发现新的版本是否要更新该软件", "平浪舟现货程序化交易--更新提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                        if (dr == DialogResult.OK)
                        {
                            //打开下载窗口
                            // Application.Run(new DownUpdate());

                            //启动安装程序                       
                            System.Diagnostics.Process.Start(Application.StartupPath + @"Upgrade_Form.exe");

                            Application.Exit();
                        }
                        else
                        {
                            //若用户取消,打开初始界面
                            anshield_Login login = new anshield_Login();
                            if (login.ShowDialog() == DialogResult.OK)
                            {
                                Application.Run(new Main_AutoFutures());
                            }
                        }
                    }
                    else
                    {
                        //若服务器版本低于或相等客户端,打开初始界面
                        anshield_Login login = new anshield_Login();
                        if (login.ShowDialog() == DialogResult.OK)
                        {
                            Application.Run(new Main_AutoFutures());
                        }
                    }
                }
                catch
                {
                    XtraMessageBox.Show("网络链接失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                }
            }

         
            /// <summary>
            /// 应用程序的主入口点。
            /// </summary>
            [STAThread]
            static void Main()
            {
               
                //保证同时只有一个客户端在运行  
                System.Threading.Mutex mutexMyapplication = new System.Threading.Mutex(false, "jigou_plz.exe");
                if (!mutexMyapplication.WaitOne(100, false))
                {
                    XtraMessageBox.Show("程序" + Application.ProductName + "已经在运行!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);              
                    return;
                }
                else
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    //汉化
                    hugengyong hu = new hugengyong();              
                    DevExpress.UserSkins.OfficeSkins.Register();
                    DevExpress.Skins.SkinManager.EnableFormSkins();
                    DevExpress.UserSkins.BonusSkins.Register();

                    LoadMath();
                    }
            }
        }
    }

     第二部分:升级程序代码如下:

      //debug目录,用于存放压缩文件
            string path = Application.StartupPath;

     private void btnDown_Click(object sender, EventArgs e)
            {
                string zipFile = path + @"jigou_plz.zip";
                //关闭原有的应用程序 
                killProess();
               
                btnDown.Enabled = false;
                button2.Enabled = false;
                //自动下载压缩包,并且解压,最后关闭当前进程,进行安装
                try
                {
                    //下载自动更新
                    string downUrl = ConfigurationManager.ConnectionStrings["DownUrl"].ConnectionString.ToString().Trim();
                    if (!string.IsNullOrEmpty(downUrl))
                    {
                        DownloadFile(downUrl, zipFile, progressBar1, label1);
                    }
                    else
                    {
                        MessageBox.Show("Config中的下载路径配置错误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                catch
                {
                    MessageBox.Show("当前没有网络或者文件地址不正确");
                    return;
                }         
                //解a压1
                try
                {
                    //关闭原有的应用程序 
                    killProess();
                    //unCompressRAR(path, path, "setup.rar", true);
                    BaseClase.Zip.UnZip(zipFile, path, "", true,true);
                  
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
                if (MessageBox.Show("升级完成!,请重新登陆!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK)
                {
                    FileInfo file = new FileInfo(path + @"Anshield_AutoFutures.exe");//文件地址
                    if (file.Exists)
                    {
                        Process.Start(path + @"Anshield_AutoFutures.exe");
                    }            
                    Application.Exit();
                }
              
            }
            /// <summary>       
            /// c#.net 下载文件       
            /// </summary>       
            /// <param name="URL">下载文件地址</param>      
            ///
            /// <param name="Filename">下载后的存放地址</param>       
            /// <param name="Prog">用于显示的进度条</param>       
            ///
            public void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1)
            {
                float percent = 0;
                try
                {
                    System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                    System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                    long totalBytes = myrp.ContentLength;
                    if (prog != null)
                    {
                        prog.Maximum = (int)totalBytes;
                    }
                    System.IO.Stream st = myrp.GetResponseStream();
                    System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                    long totalDownloadedByte = 0;
                    byte[] by = new byte[1024];
                    int osize = st.Read(by, 0, (int)by.Length);
                    while (osize > 0)
                    {
                        totalDownloadedByte = osize + totalDownloadedByte;
                        System.Windows.Forms.Application.DoEvents();
                        so.Write(by, 0, osize);
                        if (prog != null)
                        {
                            prog.Value = (int)totalDownloadedByte;
                        }
                        osize = st.Read(by, 0, (int)by.Length);

                        percent = (float)totalDownloadedByte / (float)totalBytes * 100;
                        label1.Text = "下载进度" + percent.ToString() + "%";
                        System.Windows.Forms.Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息
                    }
                    label1.Text = "下载完成。安装中... ...";
                    so.Flush();//将缓冲区内在写入到基础流中
                    st.Flush();//将缓冲区内在写入到基础流中
                    so.Close();
                    st.Close();
                }
                catch (System.Exception)
                {
                    throw;
                }
            }

     /// <summary>
            /// 关闭原有的应用程序
            /// </summary>
            private void killProess()
            {
                this.label1.Text = "正在关闭程序....";
                System.Diagnostics.Process[] proc = System.Diagnostics.Process.GetProcessesByName("Anshield_AutoFutures");
                //关闭原有应用程序的所有进程
                foreach (System.Diagnostics.Process pro in proc)
                {
                    pro.Kill();
                }
            }

    zip压缩文件解压方法类

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    using System.IO.Compression;
    using ICSharpCode.SharpZipLib.Zip;

    namespace Upgrade_Form.BaseClase
    {
        class Zip
        {
        
            /// <summary>
            /// 解压缩一个 zip 文件。
            /// </summary>
            /// <param name="zipedFile">zip文件路径</param>
            /// <param name="strDirectory">解压路径</param>
            /// <param name="password">zip文件的密码</param>
            /// <param name="overWrite">是否覆盖已存在的文件。</param>
            /// <param name="delteFile">解压后是否删除文件</param>
            public static void UnZip(string zipedFile, string strDirectory, string password, bool overWrite,bool delteFile)
            {
                //路径不存在则创建
                if (Directory.Exists(strDirectory) == false)
                {
                    Directory.CreateDirectory(strDirectory);
                }
                if (strDirectory == "")
                    strDirectory = Directory.GetCurrentDirectory();
                if (!strDirectory.EndsWith("\"))
                    strDirectory = strDirectory + "\";

                using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipedFile)))
                {
                    s.Password = password;
                    ZipEntry theEntry;

                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        string directoryName = "";
                        string pathToZip = "";
                        pathToZip = theEntry.Name;

                        if (pathToZip != "")
                            directoryName = Path.GetDirectoryName(pathToZip) + "\";

                        string fileName = Path.GetFileName(pathToZip);

                        Directory.CreateDirectory(strDirectory + directoryName);

                        if (fileName != "")
                        {
                            if ((File.Exists(strDirectory + directoryName + fileName) && overWrite) || (!File.Exists(strDirectory + directoryName + fileName)))
                            {
                                using (FileStream streamWriter = File.Create(strDirectory + directoryName + fileName))
                                {
                                    int size = 2048;
                                    byte[] data = new byte[2048];
                                    while (true)
                                    {
                                        size = s.Read(data, 0, data.Length);

                                        if (size > 0)
                                            streamWriter.Write(data, 0, size);
                                        else
                                            break;
                                    }
                                    streamWriter.Close();
                                }
                            }
                        }
                    }

                    s.Close();
                }
                if (delteFile == true)
                {
                    File.Delete(zipedFile);
                }
            }

        }
    }

    出处:https://blog.csdn.net/lybwwp/article/details/8426022

  • 相关阅读:
    20170926-构建之法:现代软件工程-阅读笔记
    我的swift的ui标签
    内存管理:内存泄漏和空悬指针
    闭包
    泛型,修饰符和异常处理
    类型转换,接口和扩展
    初始化2
    类的继承和初始化1
    枚举与可选值
    swift中的类和结构
  • 原文地址:https://www.cnblogs.com/mq0036/p/10431931.html
Copyright © 2011-2022 走看看