C# winfom自动更新

之前写过一个winform在线更新的文章,使用ClickOnce发布方式,但是在实际运行的过程中,有些dll文件缺失导致部分功能无法使用,现在介绍另外一个方法,使用代码更新。

实现思路:

所有的在线更新都是比对版本号,再进行程序更新;使用代码也是一样的思路,

1、在iis上部署网站,存储正式运行程序的压缩包,以及版本文件

2、编写升级软件,获取当前配置下的版本,与iis上的版本文件中的版本号进行比对,版本文件低时,就进行压缩包的下载

3、下载完成后,进行解压(FastZip 解压,压缩包进行压缩的时候,必须是zip文件,否则解压会报错),然后运行exe程序,并关闭升级程序

直接附代码:

1、程序配置文件(在iis对应的目录下创建 updates.json 文件)

{
"latestversion": "3.0.3",
"downloadurl":"http://127.0.0.1:8091/FD3_WcsClient.zip",
"changelog": "更改日志",
"mandatory": true
}

2.、新建实体类,对应服务器中的 updates.json 文件

复制代码
    /// <summary>
    /// 更新信息
    /// </summary>
    public class UpdateEntity
    {

        /// <summary>
        /// 提供更新的版本号
        /// </summary>
        public string latestversion { get; set; }

        /// <summary>
        /// 更新包的下载路径,,这里将需要更新的文件压缩成zip文件
        /// </summary>
        public string downloadurl { get; set; }

        /// <summary>
        /// 更新日志
        /// </summary>
        public string changelog { get; set; }

        /// <summary>
        /// 是否是强制更新
        /// </summary>
        public bool mandatory { get; set; }
    }
复制代码

3、附窗体截图(中间为进度条 progressBar控件)

 

 4、主程序文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
using ICSharpCode.SharpZipLib.Zip;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace OnlineUpdateDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        //-当前版本号
        private string NowVersion;
        //-解压到的目录
        private string InstallPath;
        //-程序启用地址
        private string StartPath;
 
 
        private UpdateEntity updateEntity = null;
 
        private void Form1_Load(object sender, EventArgs e)
        {
            //获取当前版本号
            NowVersion = System.Configuration.ConfigurationManager.AppSettings["Version"];
            //获取解压到的目录
            InstallPath = System.Configuration.ConfigurationManager.AppSettings["InstallPath"];
            //获取程序启用地址
            StartPath = System.Configuration.ConfigurationManager.AppSettings["StartPath"];
 
            //获取更新配置参数内容
            string UpdateEntityUrl = System.Configuration.ConfigurationManager.AppSettings["UpdateEntityUrl"];
            string updateJson = getHtml(UpdateEntityUrl);
            updateEntity = JsonConvert.DeserializeObject<UpdateEntity>(updateJson);
 
            //显示版本号
            this.label_NowVersion.Text = NowVersion;
            this.label_NextVersion.Text = updateEntity.latestversion;
 
            if (string.Compare(updateEntity.latestversion, NowVersion) > 0)
            {
                label_message.Text = "有新版本";
 
                //是否强制更新
                if (updateEntity.mandatory)
                {
                    Btn_Next_Click(null, null);
                }
            }
            else
            {
                label_message.Text = "没有更新版本了";
 
                //是否强制更新
                if (updateEntity.mandatory)
                {
                    //启动软件
                    ShowLogin();
                }
            }
        }
 
        /// <summary>
        /// 开始升级按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Next_Click(object sender, EventArgs e)
        {
            //判断值的有效性
            if (string.IsNullOrEmpty(NowVersion)) return;
            if (updateEntity == null) return;
 
            //下载程序文件到指定的目录下
            try
            {
                WebClient wc = new WebClient();
                wc.DownloadProgressChanged += Wc_DownloadProgressChanged;
                Uri uri = new Uri(updateEntity.downloadurl);
 
                if (!Directory.Exists(InstallPath))
                {
                    Directory.CreateDirectory(InstallPath);
                }
                wc.DownloadFileAsync(uri, InstallPath + "FD3_WcsClient.zip");
            }
            catch (Exception er)
            {
                MessageBox.Show("下载失败:" + er.Message);
            }
        }
 
        /// <summary>
        /// 退出程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
            this.Dispose();
        }
 
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Login_Click(object sender, EventArgs e)
        {
            ShowLogin();
        }
 
        private void Wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            Action act = () =>
            {
                this.progressBar1.Value = e.ProgressPercentage;
                label_message.Text = "正在下载.....";
            };
            this.Invoke(act);
 
            //下载完成后解压并覆盖
            if (e.ProgressPercentage == 100)
            {
                label_message.Text = "正在解压.....";
 
                try
                {
 
                    //压缩包路径
                    string zipFileName = InstallPath + "FD3_WcsClient.zip";
                    //解压路径
                    string targetDirectory = InstallPath;
 
                    var result = Compress(targetDirectory, zipFileName, "");
                    if (result == "Success!")
                    {
                        progressBar1.Value = 100;
                        this.label_message.Text = "更新完成";
 
                        //删除压缩包
                        //File.Delete(zipFileName);
 
                        //更新配置文件的信息
                        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                        config.AppSettings.Settings["Version"].Value = updateEntity.latestversion;
                        config.Save(ConfigurationSaveMode.Full);
                        ConfigurationManager.RefreshSection("Version");
 
                        //启动软件
                        ShowLogin();
                    }
                    else
                    {
                        MessageBox.Show("更新失败:" + result);
                        this.Close();
                    }
 
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
 
        /// <summary>
        /// 通过ip获取json数据信息
        /// </summary>
        /// <param name="url">网址</param>
        /// <returns></returns>
        public string getHtml(string url)
        {
            try
            {
                string pageHtml = "";
 
                //获取或设置用于向Internet资源的请求进行身份验证的网络凭据
                WebClient MyWebClient = new WebClient();
 
                //从指定网站下载数据
                Byte[] pageData = MyWebClient.DownloadData(url);
                MemoryStream ms = new MemoryStream(pageData);
                using (StreamReader sr = new StreamReader(ms, Encoding.UTF8))
                {
                    pageHtml = sr.ReadLine();
                }
                return pageHtml;
            }
            catch (Exception)
            {
                MessageBox.Show("网络连接失败");
                throw;
            }
        }
 
        /// <summary>
        /// 解压Zip
        /// </summary>
        /// <param name="DirPath">解压后存放路径</param>
        /// <param name="ZipPath">Zip的存放路径</param>
        /// <param name="ZipPWD">解压密码(null代表无密码)</param>
        /// <returns></returns>
        public string Compress(string DirPath, string ZipPath, string ZipPWD)
        {
            string state = "Fail!";
            if (!Directory.Exists(DirPath)) return state;
            if (!File.Exists(ZipPath)) return state;
            try
            {
                FastZip fastZip = new FastZip();
                fastZip.ExtractZip(ZipPath, DirPath, "");
                state = "Success!";
            }
            catch (Exception ex)
            {
                state += "," + ex.Message;
            }
            return state;
        }
 
        /// <summary>
        /// 打开wcs程序
        /// </summary>
        public void ShowLogin()
        {
            //启动软件
            System.Diagnostics.Process.Start(StartPath);
            GC.Collect();
            Application.Exit();
        }
 
        
    }
}

5、配置文件内容

复制代码
    <appSettings>
        <!--当前版本号-->
        <add key="Version" value="3.0.2" />
        <!--程序集版本配置信息-->
        <add key="UpdateEntityUrl" value="http://192.168.31.2:8091/updates.json" />
        <!--解压到的目录-->
        <add key="InstallPath" value="D:/WCS_Project/" />
        <!--程序启用地址-->
        <add key="StartPath" value="D:/WCS_Project/福鼎物流控制系统.exe" />

    </appSettings>
复制代码

 

  

posted @   搬砖工具人  阅读(842)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示