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

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

C# 自动升级的更多相关文章

  1. Ionic实战 自动升级APP(Android版)

    Ionic 框架介绍 Ionic是一个基于Angularjs.可以使用HTML5构建混合移动应用的用户界面框架,它自称为是"本地与HTML5的结合".该框架提供了很多基本的移动用户 ...

  2. 黄聪:C#Winform程序如何发布并自动升级(图解)

    有不少朋友问到C#Winform程序怎么样配置升级,怎么样打包,怎么样发布的,在这里我解释一下打包和发布关于打包的大家可以看我的文章C# winform程序怎么打包成安装项目(图解)其实打包是打包,发 ...

  3. NetworkComms 文件上传下载和客户端自动升级(非开源)

    演示程序下载地址:http://pan.baidu.com/s/1geVfmcr 淘宝地址:https://shop183793329.taobao.com 联系QQ号:3201175853 许可:购 ...

  4. 【转】C#Winform程序如何发布并自动升级(图解)

    有不少朋友问到C#Winform程序怎么样配置升级,怎么样打包,怎么样发布的,在这里我解释一下打包和发布关于打包的大家可以看我的文章C# winform程序怎么打包成安装项目(图解)其实打包是打包,发 ...

  5. 自动升级系统OAUS的设计与实现(续) (附最新源码)

    (最新OAUS版本请参见:自动升级系统的设计与实现(续2) -- 增加断点续传功能) 一.缘起 自从 自动升级系统的设计与实现(源码) 发布以后,收到了很多使用者的反馈,其中最多的要求就是希望OAUS ...

  6. Android 实现应用升级方案(暨第三方自动升级服务无法使用后的解决方案)

    第三方推送升级服务不再靠谱: 以前在做Android开发的时候,在应用升级方面都是使用的第三方推送升级服务,但是目前因为一些非技术性的问题,一些第三方厂商不再提供自动升级服务,比如友盟,那么当第三方推 ...

  7. c/s 自动升级(WebService)

    首先声明,本人文笔不好,大家见笑,欢迎高手吐槽. 做c/s开发肯定会遇到的就是自动升级功能,而这实现方式是非常多. 本文使用 webservice的方式来提供升级服务 首先准备服务 为了方便我们专门用 ...

  8. C#学校班级自动升级实现代码

    代码逻辑如下: //班级自动升级 //获取该学校还没有毕业的班级 List<ClassInfoes> classinfoeslist = classinfoesbll.GetList(Sc ...

  9. C#Winform程序如何发布并自动升级(图解)

    C#Winform程序如何发布并自动升级(图解)     有不少朋友问到C#Winform程序怎么样配置升级,怎么样打包,怎么样发布的,在这里我解释一下打包和发布 关于打包的大家可以看我的文章C# w ...

  10. SNF开发平台WinForm之八-自动升级程序部署使用说明-SNF快速开发平台3.3-Spring.Net.Framework

    9.1运行效果: 9.2开发实现: 1.首先配置服务器端,把“SNFAutoUpdate2.0\服务器端部署“目录按网站程序进行发布到IIS服务器上. 2.粘贴语句,生成程序 需要调用的应用程序的Lo ...

随机推荐

  1. CSS特性

    css的特性 css具有两大特性:继承性和层叠性 1.继承性 指的是子元素继承父元素的样式,但没有所有的样式都可以继承(那样就太可怕了) 所以具有继承性的属性主要分为三大类 a.文本属性 font-s ...

  2. Aimbat安装

    1:Pysmo下的sac和aimbat需要放在和前面的toolkits 相同的地方,Python就能找到: 在安装obspy时,需要装yum-plugin-copr; 方法在网址: https://c ...

  3. linux自动更新代码,自动备份数据库,打包应用发布

    切换root用户 sudo su - 1.安装svn,mysql yum install subversion yum install mysql 2.安装 maven 下载:百度云盘地址为 http ...

  4. HDU 2063 (二分图最大匹配)

    RPG girls今天和大家一起去游乐场玩,终于可以坐上梦寐以求的过山车了.可是,过山车的每一排只有两个座位,而且还有条不成文的规矩,就是每个女生必须找个个男生做partner和她同坐.但是,每个女孩 ...

  5. shell脚本实例-for实现批量主机的探测

    #!/usr/bin/bash >ip.txt for i in {2..254} do { ip=192.168.234.$i ping -c1 -W1 $ip &>/dev/n ...

  6. 启动和停止mysql的正确姿势

    1.如果是用脚本起的.那就用脚本停 2.最好用mysql_safe起,mysqladmin -uroot -p shutdown -S /tmp/mysql.sock停 mysqld_safe --d ...

  7. Day18作业及默写

    人狗大战 #!/usr/bin/env python # encoding: utf-8 # Author: MeiMeiLong <2559184081@qq.com> # Create ...

  8. python操作sqlite3的几项问题分析

    不同数据库还是有各自特点的,之前自以为熟悉mysql,然后全都照搬到sqlite3上,这样果然是不行的.笔者就近期在使用sqlite3时碰到的问题做了总结分析,并给出相应解决方法,供大家参考. 1.如 ...

  9. IOS safari 浏览器 时间乱码(ios时间显示NaN) 问题解决

    问题一: 项目中遇到一个关于日期时间在ios中乱码在安卓中安然无恙的问题,焦躁了半天 问题如上图,通过用户选择的时间和当天的天数相加然后在ios上就是乱码 这个界面运用了日期类型的计算,当我们用Jav ...

  10. 关于Q-LEARNING的优化

    Q-LEARNING 最后得到的一个图寻路最佳路径:---直接转化为图关于多顶点深度遍历热度传递 V(level+1) = 0.8 * Max(Vi(level))   这个方法可以在O时间收敛 原方 ...