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

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. caffe blob

    Blob,包括输入数据.输出数据.权值等: Blob是Caffe中处理和传递实际数据的数据封装包,并且在CPU与GPU之间具有同步处理能力.从数学意义上说,blob是按C风格连续存储的N维数组. ca ...

  2. Dom操作注意事项

    Dom操作注意事项 基本概念: 在 HTML DOM (文档对象模型)中,每个部分都是节点: 文档本身是文档节点 所有 HTML 元素是元素节点 所有 HTML 属性是属性节点 HTML 元素内的文本 ...

  3. 关于Java的接口

    其实刚开始听到接口的时候不解其意,为什么要有接口这个东西,加之老师上课我可能没仔细听(或者时间长了忘了?),这次看到了“用接口设计并实现圆,三角形,矩形的面积与周长计算”这个题目的代码,它将接口定义在 ...

  4. CodeForces - 631C (截取法)

    C. Report time limit per test 2 seconds memory limit per test 256 megabytes input standard input out ...

  5. uiautomator2 获取APP Toast内容

    前言:appium必须是1.6以上的版本 环境(安装和安装都可以运行成功,我也不确定要不要这个): 1.抓到toast需要安装uiautomator2,安装npm:npm install -g cnp ...

  6. L253 Valentine's Day

    Are you ready for Valentine's Day, my fellow stargazers? Not sure if you know this, but the astrolog ...

  7. count函数详细介绍

    select count(字段) from 表名; #得到字段中is not null的行数 select count(*)from 表名; #任何列,只要有一个非null就会被统计上.全为null( ...

  8. express框架以及配置项

    以上命令会将 Express 框架安装在当前目录的 node_modules 目录中, node_modules 目录下会自动创建 express 目录.以下几个重要的模块是需要与 express 框 ...

  9. Electron_01

    1.通过 https://electron.atom.io/  下载  electron-v1.4.15-win32-x64.zip 之后 2.通过 asar pack “你的项目文件夹” app.a ...

  10. 2016 多校联赛7 Joint Stacks (优先队列)

    A stack is a data structure in which all insertions and deletions of entries are made at one end, ca ...