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、主程序文件
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>

浙公网安备 33010602011771号