C# winForm 软件自动升级实现方式

2023-05-16

对于C#winform开发者来说,软件自动升级功能是一个很重要的功能。作者根据自身经验,和大家分享一下软件升级的实现方式。

注意:本文主要介绍通过WebService升级软件。作者的另一篇通过FTP方式升级软件的介绍可在作者的另一篇文中查看https://jingyan.baidu.com/article/4dc4084842d8fec8d946f1ca.html。

第一步:首先建立一个Winform程序,这里叫做AppUpdatePC.在Form1的.cs文件中复制一下代码:这里通过读取主程序的文件版本和升级包里面的升级程序的文件版本做匹配,来进行升级判断。如果两者程序版本一致,则进行升级,如果不一致,则不升级

       
        string url = " http://XXX(服务器地址)/update/pcapp/";这里改为你的WebService地址。

        string fUpdate = @"";

        string AppName = "BarcodePrint";
        string m_workPath = "";
        string xmlFile = null;

        public Form1()
        {
            InitializeComponent();

            //m_workPath = Assembly.GetExecutingAssembly().GetName().CodeBase.Substring(0, Assembly.GetExecutingAssembly().GetName().CodeBase.LastIndexOf(@"/") + 1).Replace(@"file:///", "");


            //Release版本
            //m_workPath = System.IO.Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            //m_workPath = System.IO.Path.GetDirectoryName(m_workPath);
            m_workPath = AppDomain.CurrentDomain.BaseDirectory;
            //m_workPath = Application.StartupPath;
            //xmlFile = m_workPath;

            //MessageBox.Show(m_workPath);
            //string workPath = System.IO.Path.Combine(filePath, "Config.xml");

            //DataSet ds = new DataSet();
            //ds.ReadXml( m_workPath + "config.xml");
            //url = ds.Tables[0].Rows[0]["WebServiceURL"].ToString();
            //url = url.Substring(0, url.IndexOf("Service"));
            //url += "update/Update_TKE_HT/";
            //AppName = ds.Tables[0].Rows[0]["AppName"].ToString();

            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Download();
        }
        private void Download()
        {
            //获取本地应用程序目录
            DirectoryInfo theFolder = new DirectoryInfo(Path.GetDirectoryName(this.m_workPath + "\\"));
            //获取服务器目录
            //DirectoryInfo theFolder = new DirectoryInfo(fUpdate);

            try
            {
                this.button1.Enabled = false;
                this.button2.Enabled = false;
                this.Refresh();

                foreach (FileInfo theFile in theFolder.GetFiles())
                {
                    DownloadFile(theFile.Name, url + theFile.Name);
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
            finally
            {
                this.button1.Enabled = true;
                this.button2.Enabled = true; 
            }
            //启动程序 
            System.Diagnostics.Process.Start(this.m_workPath + "\\" + AppName + ".exe", "");
            Application.Exit();
            Close();

        }
        private void DownloadFile(string FileName, string strUrl)
        {
            HttpWebRequest request;
            HttpWebResponse response = null;
            try
            {
                System.Globalization.DateTimeFormatInfo dfi = null;
                System.Globalization.CultureInfo ci = null;
                ci = new System.Globalization.CultureInfo("zh-CN");
                dfi = new System.Globalization.DateTimeFormatInfo();

                //WebRequest wr = WebRequest.Create("");

                //System.Net.WebResponse w=wr.
                DateTime fileDate;
                long totalBytes;
                DirectoryInfo theFolder = new DirectoryInfo(Path.GetTempPath() + "");
                string fileName = theFolder + FileName;

                request = (HttpWebRequest)HttpWebRequest.Create(strUrl);

                response = (HttpWebResponse)request.GetResponse();

                if (response == null)
                    return;
                fileDate = response.LastModified;
                //if (File.GetLastWriteTime(m_workPath+"\\"+FileName) >= fileDate)
                //{
                //    response.Close();
                //    return;
                //}
                totalBytes = response.ContentLength;
                progressBar1.Maximum = Convert.ToInt32(totalBytes);

                Stream stream = response.GetResponseStream();
                FileStream sw = new FileStream(fileName, FileMode.Create);
                int totalDownloadedByte = 0;
                Byte[] @by = new byte[1024];
                int osize = stream.Read(@by, 0, @by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    Application.DoEvents();
                    sw.Write(@by, 0, osize);
                    progressBar1.Value = totalDownloadedByte;
                    osize = stream.Read(@by, 0, @by.Length);
                }
                sw.Close();
                stream.Close();

                //System.Diagnostics.Process[] proc = System.Diagnostics.Process.GetProcessesByName(AppName);

                关闭原有应用程序的所有进程 
                //foreach (System.Diagnostics.Process pro in proc)
                //{
                //    pro.Kill();
                //}


                //DirectoryInfo theFolder = new DirectoryInfo(Path.GetTempPath() + "ysy");
                if (theFolder.Exists)
                {
                    foreach (FileInfo theFile in theFolder.GetFiles())
                    {
                        //如果临时文件夹下存在与应用程序所在目录下的文件同名的文件,则删除应用程序目录下的文件 
                        if (File.Exists(this.m_workPath + "\\" + Path.GetFileName(theFile.FullName)))
                        {
                            File.Delete(this.m_workPath + "\\" + Path.GetFileName(theFile.FullName));
                            //将临时文件夹的文件移到应用程序所在的目录下 
                            File.Move(theFile.FullName, this.m_workPath + "\\" + Path.GetFileName(theFile.FullName));

                        }
                    }
                }
                //File.SetLastWriteTime(FileName, fileDate);

            }
            catch (Exception)
            {
                if (response != null)
                    response.Close();
                //MessageBox.Show(ex.Message);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //System.Diagnostics.Process.Start(this.m_workPath + "\\" + AppName + ".exe");
            this.Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Download();

        }

        public int setConfig(string pro, string par, string val)
        {
            XmlDocument xd = new XmlDocument();
            xd.Load(xmlFile);
            try
            {
                xd.FirstChild.SelectSingleNode(pro).SelectSingleNode(par).InnerText = val;

                xd.Save(xmlFile);
                xd = null;
                return 0;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
        public int setParConfig(string ItemName, string ItemValue)
        {
            XmlDocument xd = new XmlDocument();
            xd.Load(xmlFile);
            try
            {
                xd.FirstChild.SelectSingleNode(ItemName).InnerText = ItemValue;

                xd.Save(xmlFile);
                xd = null;
                return 0;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
        public string getConfig(string pro, string par)
        {
            XmlDocument xd = new XmlDocument();
            xd.Load(xmlFile);
            try
            {
                string str = xd.FirstChild.SelectSingleNode(pro).SelectSingleNode(par).InnerText;
                xd = null;
                return str;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
      
        private string GetVersion()
        {
            string version = "";

            try
            {
                string strVersionPath = this.m_workPath + "version.txt";
                StreamReader sw = new StreamReader( strVersionPath );
                version = sw.ReadLine();
            }
            catch ( Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            return version;
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            Download();
        }

       
    }

第二步:在系统登录时,进行系统的版本号判断。这里写一个判断版本号是否一致的方法,来进行版本号的匹配,该代码写在WebService的实现代码中,中间的调用过程,大家可根据自己的项目自身情况,进行调用代码的编写。判断版本号一致的代码如下:

       public static bool VerifyVersion(string[] FileVersion, string[] FileName)
        {
            LogNote ln = null;

            try
            {
                string strVersion = null;
                ln = new LogNote(AppDomain.CurrentDomain.BaseDirectory + "barcode.log");
                for (int i = 0; i < FileName.Length; i++)
                {
                    FileVersionInfo fv = FileVersionInfo.GetVersionInfo(AppDomain.CurrentDomain.BaseDirectory + "\\update\\" + FileName[i]);
                    strVersion = fv.FileVersion;

                    //strVersion = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory+"\\update\\" + FileName[i]).GetName().Version.ToString();
                    //Version v = new Version("");
                    ln.Write(i.ToString(), FileVersion + "/" + strVersion);
                    if (FileVersion[i] != strVersion)
                    {
                        return false;
                    }
                }
                return true;
            }
            catch (Exception er)
            {
                return true;
            }

        }

WebService声明的代码如下:

    [WebMethod]
    public bool verfiyVersion(string[] Version, string[] FileName)
    {
        return CommonDA.VerifyVersion(Version, FileName);
    }

WInform程序的接口实现代码如下:

        public bool verifyVersion(string[] Version, string[] FileName)
        {
            Common co = Common.GetCommon();
            return co.m_service.verfiyVersion(Version, FileName);
        }

winform程序的函数调用代码如下所示:

                string[] fileName = new string[2];
                string[] fileVersion = new string[2];

                fileName[0] = "\\htapp\\HTApp.exe";程序路径
                fileVersion[0] = this.labversion.Text;
                //fileName[1] = "U8Business.dll";
                //fileVersion[1] = this.labDllversion.Text;

                if (!Common.CurrentUser.verifyVersion(fileVersion, fileName))
                {
                    MessageBox.Show("程序有新的版本,请确定后更新!");
                    System.Diagnostics.Process.Start(System.IO.Path.GetDirectoryName
                        (System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).ToString() + "\\AppUpdate.exe", "123");
                    Application.Exit();
                    Close();
                    return;
                }

第三步:修改程序版本号,完成升级包的制作。打开主程序项目的目录,点击“propertiey”,打开AssmsblyInfo类,修改版本号的信息,如下所示,修改之后保存,重新生成程序,然后就可以把Bin/Debug目录下的新程序放到WebService的相对应的更新目录下。带程序启动时,会自动监测程序的版本号,并且进行升级。

// 程序集的版本信息由下面四个值组成:
//
//      主版本
//      次版本 
//      内部版本号
//      修订号
//
// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.2.2")]
[assembly: AssemblyFileVersion("1.2.2.2")]

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# winForm 软件自动升级实现方式 的相关文章

  • C# winform 捕获全局异常

    using System using System Collections Generic using System Windows Forms using System IO namespace GobalException static
  • 用C#实现MVC+观察者模式(WINFORM)

    用C 实现MVC xff08 Model View Control xff09 模式介绍 益处 下载案例 xff1a https download csdn net download gigizhongyan 13011332 在我们的开发
  • 03--C#Winform--让你的button控件更漂亮

    最近做一个小的项目 xff0c 想要将部门的各种资料 各种辅助软件汇总一下 xff0c 需要使用到很多的button的控件 xff0c 然后效果是这样的 xff1a 额 这效果太难看了 xff0c 不符合小姐姐的审美 xff0c 就打算深入
  • winform-日记

    1 Form的属性TopLevel设置为false xff0c 就相当于usercontrol的功能了 xff0c 可以被包含在容器中 xff0c 只不过需要动态在代码中加载 xff0c usercontrol则可拖拽
  • C#WinForm

    WinForm 是 Windows Form 的简称 xff0c 是基于 NET Framework 平台的客户端 xff08 PC软件 xff09 开发技术使用 C 编程 C WinForm 编程需要创建Windows窗体应用程序项目 W
  • winform窗体

    一 winform介绍 WinForm xff0c 是 Net开发平台中对Windows Form的一种称谓 WinForm是窗体应用程序 xff0c 由若干个窗体应用组成 xff0c 基于C S架构 二 winform的使用 xff08
  • winform怎样设置comboBox默认值

    combox是开发winform常用的组件之一 xff0c 如何添加他的默认值呢 xff01 方法 步骤 新建一个windows窗体应用程序 xff0c 这里项目命名为test01 在默认打开的Form1中 xff0c 在左边的工具箱拖拉两
  • 打造属于自己的正则表达式

    概述 首先需要说明的一点 无论是Winform 还是Webform 都有很成熟的日历控件 无论从易用性还是可扩展性上看 日期的选择和校验还是用日历控件来实现比较好 前几天在CSDN多个版块看到需要日期正则的帖子 所以整理了这篇文章 和大家一
  • Winform各控件详解(笔记)

    DataGridView简称DGV http www cnblogs com 08shiyan archive 2010 08 10 1796768 html
  • Winform实现ComboBox模糊查询

    1 新增项目 using System using System Collections Generic using System ComponentModel using System Data using System Drawing
  • C#客户端Json转DataTable

    之前我们有讨论过c 是如何处理json的 在我的客户端中 需要接收服务端的数据 并且用列表展示出来 列表控件我采用的是winfrom自带的DataGridView 从服务端得到的响应是一串json字符串 为了提高效率和简洁代码 我不想采用解
  • C#winform——添加不同语言环境下的resx,使得显示文本能随语言环境变化

    添加不同语言环境下的resx 添加不同语言resx文件的两种情形 窗体控件 非窗体控件 为窗体控件添加不同语言resx文件 为非窗体控件添加不同语言resx文件 添加不同语言resx文件的两种情形 窗体控件 1 如下所示 需要在不同语言环境
  • winform 登录跳转页面

    登录成功后跳转 改两个地方就可以解决而 第一个 上面的判断是登录成功与否 跳转需要的就是一句 当前页 改变DialogResult this DialogResult DialogResult OK 第二个 在Program cs里面 st
  • Winform ListView控件用法

    用法一 1直接从工具箱里把ListView拖到控件上 2可在窗体的Load 事件里 写如下代码 设置一些常用属性 listView1 View View Details listView1 LabelEdit true listView1
  • 控制winform控件textbox(自写的那个),限制输入两位小数

    有个FloatLength属性 直接修改为2 即可 如果是3位小数的话 直接修改为3即可
  • C# WINFORM嵌入CHROME浏览器(CEFSHARP)

    在开发过程中经常需要在程序中嵌入浏览器控件用于访问网页 Visual Studio中自带了一个webbrowser控件 但无奈这个控件是调用用户电脑上的IE浏览器来实现的 如果用户装的是低版本IE 比如Win7的IE8 很多新的网页标准就无
  • Winform 编写一个读取并解析csv的程序

    众所周知 CSV是一种通用的 相对简单的文件格式 被用户 商业和科学广泛应用 所以在制作游戏时 可能会用到CSV来记录各个物品的数据 就像这样 ID Name Description ItemType 01 无机化学 第四版 风靡于各大高校
  • WinForm 编程中控件的使用小技巧(splitter实现窗口分区域,改变Button的形状)

    一 Splitter 控件的主要作用就是将窗口分区并可以调节区域大小 比如 我想将窗口分为左右两个区域 并可以调节两个区域所占的比例 操作流程如下 1 新建一个窗口 Form1 2 在Form1中添加一个Panel控件Panel1 并将其D
  • C#开发Windows窗体应用程序的步骤

    使用C 开发应用程序时 一般包括创建项目 界面设计 设置属性 编写程序代码 保存项目 程序运行等6个步骤 1 创建项目 在Visual Studio2017开发环境中选择 文件 新建 项目 菜单 弹出 新建项目 对话框 如图8 1所示 图8
  • winform记录

    SpeechSynthesizer 下边代码多次调用 会导致内存溢出outofmemory SpeechSynthesizer 需要改为全局静态 private void button Click object sender EventAr

随机推荐

  • ubuntu误删文件造成软件包信息列表损坏无法更新或安装文件

    因为一开始不知到如何彻底卸载软件包 xff0c 误把文件目录删除 xff0c 造成了软件包信息列表损坏 xff0c 系统无法使用apt get 命令 xff0c 无论实施更新或安装还是卸载都会提示软件包信息列表损坏 xff0c 建议重新安装
  • Docker镜像转换成Dockerfile

    通常我们会通过dockerfile构建docker xff0c 但是我们需要使用dockerfile时 xff0c 想还原其dockerfile xff0c 我们可以使用如下命令 docker run v var run docker so
  • 使用iperf测试网络速度--windows

    下载 下载iperf的Windows版本 xff1a iperf官网地址 这里下载的版本是iperf 3 1 3 win32 xff0c 电脑使用的是XP系统 下载文件中有cygwin1 dll xff0c cyggcc s 1 dll x
  • [最新]ubuntu22.04安装kubernetes1.25 k8s1.25

    条件 2G内存2 CPU网络连接 xff08 内网公网都可以 xff09 唯一的主机名 xff0c mac地址6443 xff0c 10650等端口禁用Swap20 GB var目录磁盘空间Sudo 用户权限 主机准备 Master Nod
  • hadoop目录介绍(各目录功能介绍)

    hadoop目录 1 bin xff1a 2 sbin3 etc4 lib5 logs6 include7 libexec8 share目录 介绍hadoop的目录 首先进入hadoop查看目录 挑重要的介绍 1 bin xff1a bin
  • Linux操作文件的系统调用

    操作文件的系统调用 1 文件操作有关的系统调用 open xff08 xff09 read xff08 xff09 write xff08 xff09 close xff08 xff09 1 xff09 open xff08 xff09 i
  • MySQL 分组查询

    文章目录 分组查询分组函数1 功能2 分类3 特点3 简单的使用4 和distinct搭配使用5 count函数的具体介绍6 和分组函数一同查询的字段有要求 分组查询1 语法2 简单的分组查询3 添加筛选条件3 1添加分组前的筛选3 2添加
  • Android-推荐一个视频播放库JZVideo

    最近项目当中有用到视频播放器这个功能 xff0c 分享一个我的开发心得 一般情况下 xff0c 我们不会去写一个视频播放器 xff0c 因为需要很多知识和播放场景考虑 分享一个我使用到的视频播放器的库 xff0c JZVideo 俗称饺子播
  • java zip压缩/解压工具类 ZipUtil

    public class ZipUtil public static void main String args throws Exception String ss 61 new String 2 ss 0 61 34 D adManag
  • echarts纯option制作自定义日历

    type 61 39 custom 39 34 tooltip 34 34 position 34 34 top 34 34 formatter 34 function p var format 61 echarts format form
  • hdparm命令详解

    hdparm命令来自于英文词组 hard disk parameters 的缩写 其功能是用于显示与设定硬盘参数 对于初次接手一块硬盘设备 了解相关性能属性有很好的帮助 nbsp 语法格式 hdparm 参数 设备名 nbsp 常用参数 n
  • Debian中配置JDK的环境

    在安装完Debian后 xff0c 系统中已经包含了open jdk但是该版本的jdk在开发java程序时有可能出现一些错误 xff0c 但对于不是开发而是普通使用的情况下一般没有太多问题 如果想要进行开发java的程序 xff0c 必须更
  • 【工控机开发】debian下安装QT及Opencv

    1 debian下安装QT开发环境 最近有需求要把虚拟机里面的程序直接在一台工控机上跑 xff0c 也就需要搭建相应的开发环境 首先说明下 xff0c debian下安装QT与在ubuntu下应该是有所区别的 xff0c 一开始偶我在deb
  • 考勤统计,一张表查询每月的员工考勤数据

    近期根据公司人事要求 写了一些关于考勤统计的报表 主要是查询员工每月的考勤数据 要求一行数据显示员工的当月的每天的考勤信息 标的样式如下 然后 根据考勤表 写了如下SQL语句 来实现报表的查询 谨以此做记录 以备后续查阅 SELECT De
  • 无法为数据库中的对象分配空间,因为‘PRIMARY‘文件组已满问题处理方式

    今天公司同事反馈 在手机APP端进行业务操作时 提示无法为数据库中的对象分配空间 因为 PRIMARY 文件组已满 如下所示 出现这个问题的原因是数据库中设置了Log日志限制了文件增长 设置如下所示 然后修改了相关设置 解决该问题 一般出现
  • C#如何连接SAP调用SAP接口函数

    在项目中我们经常会遇到SAP与其他应用系统对接的情况 xff0c 如OA对接SAP的FI HR模块 xff0c 生产系统对接SAP的MM模块等等 这里和大家介绍下C 如果调用SAP接口 xff0c 从而调用SAP接口函数 下面先贴出代码 这
  • SQLServer 分页分页查询优化方案,1秒内查询20万条数据的表

    最近在做sql分页查询的话 发现数据表中的数据量非常大的话 使用count 去统计行数的话 还是非常慢的 20多万条数据的表 用count查询 大概在9秒左右 服务器是4核8G内存的 5秒左右的时间 还是比较难以接受的 9秒时间的SQL语句
  • SQL Server 实现邮件发送功能(配置步骤及存储过程源码)

    日常企业开发中经常会遇到邮件推送的场景 我们利用SQL Server也可以实现邮件发送功能 本文主要和大家分享下利用SQL Server实现邮件发送的具体步骤 1 配置邮件服务器 配置邮件服务器 在SQL Server服务器上面选择 管理
  • Android-推荐一个视频压缩库RxFFmpeg

    最近项目当中有遇到上传视频的时候 xff0c 需要做合理压缩的需求 分享一下我使用的视频压缩库 xff0c 希望能帮助遇到同样有视频处理的需求的小伙伴 RxFFmpeg依赖 这个开源库一共有三个版本 xff0c 这里贴两个版本的依赖 xff
  • C# winForm 软件自动升级实现方式

    对于C winform开发者来说 xff0c 软件自动升级功能是一个很重要的功能 作者根据自身经验 xff0c 和大家分享一下软件升级的实现方式 注意 xff1a 本文主要介绍通过WebService升级软件 作者的另一篇通过FTP方式升级