📡 C# 版本自动更新「开发实例」

154 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第5天,点击查看活动详情


工程文件

  • Demo.csproj为自动更新功能的测试用例的 客户端主程序
  • UpdaterDemo.csproj为自动更新程序(更新功能的实现)

2022-10-21 113039.png


客户端主程序

引入命名空间

using System.Windows.Forms;
using System.Net;
using System.Diagnostics;  

工程代码

2022-10-21 113309.png

实例代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Net;
using System.Diagnostics;
​
namespace Demo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
​
            WebClient webClient = new WebClient();
​
            try
            {
                if (!webClient.DownloadString("https://pastebin.com/raw/TSxeLjzm").Contains("1.0.0"))
                {
                    if (MessageBox.Show("Looks like there is an update! Do you want to download it?", "Demo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        using (var client = new WebClient())
                        {
                            Process.Start("UpdaterDemo.exe");
                            this.Close();
                        }
                }
            }
            catch
            {
​
            }
        }
    }
}
​

生成版本号

服务器端版本号以文本形式输出

<html>
    <head>
        <body sip-shortcut-listen = "true">
            <pre style="word-wrap: break-word; white-space: pre-wrap;">1.0.0</pre>
        </body>
    </head>
</html>

自动更新程序

工程文件创建

2022-10-21 113341.png


引用命名空间

using System.Net;
using System.IO;
using System.Diagnostics;
using System.IO.Compression;

添加引用

注意 System.IO.Compression 需导入引用,否则会报错

2022-10-21 113408.png

PS:如果找不到相关引用,修改项目 目标框架版本


工程代码

主要是修改服务器端下载地址的直链,以及主程序的名称(此处以 Demo.exe/zip 为例)

2022-10-21 113431.png


发布 1.0.1 版本

构建项目

2022-10-21 113455.png

更新后版本号发布

2022-10-21 113527.png

直链提取

直链提取在线生成工具

直链下载


将本地版本转回 1.0.0

待撰......