C# winform实现自动更新
作者:刘向荣
这篇文章主要为大家详细介绍了C# winform实现自动更新的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
1.检查当前的程序和服务器的最新程序的版本,如果低于服务端的那么才能升级
2.服务端的文件打包.zip文件
3.把压缩包文件解压缩并替换客户端的debug下所有文件。
4.创建另外的程序为了解压缩覆盖掉原始的低版本的客户程序。
有个项目Update 负责在应该关闭之后复制解压文件夹 完成更新
这里选择winform项目,项目名Update
以下是 Update/Program.cs 文件的内容:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Threading;
using System.Windows.Forms;
namespace Update
{
internal static class Program
{
private static readonly HashSet<string> selfFiles = new HashSet<string> { "Update.pdb", "Update.exe", "Update.exe.config" };
[STAThread]
static void Main()
{
string delay = ConfigurationManager.AppSettings["delay"];
Thread.Sleep(int.Parse(delay));
string exePath = null;
string path = AppDomain.CurrentDomain.BaseDirectory;
string zipfile = Path.Combine(path, "Update.zip");
try
{
using (ZipArchive archive = ZipFile.OpenRead(zipfile))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (selfFiles.Contains(entry.FullName))
{
continue;
}
string filepath = Path.Combine(path, entry.FullName);
if (filepath.EndsWith(".exe"))
{
exePath = filepath;
}
entry.ExtractToFile(filepath, true);
}
}
}
catch (Exception ex)
{
MessageBox.Show("升级失败" + ex.Message);
throw;
}
if (File.Exists(zipfile))
File.Delete(zipfile);
if (exePath == null)
{
MessageBox.Show("找不到可执行文件!");
return;
}
Process process = new Process();
process.StartInfo = new ProcessStartInfo(exePath);
process.Start();
}
}
}
以下是 App.config 文件的内容:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<appSettings>
<add key="delay" value="3000"/>
</appSettings>
</configuration>
winform应用
软件版本
[assembly: AssemblyFileVersion("1.0.0.0")]
if (JudgeUpdate())
{
UpdateApp();
}
检查更新
private bool JudgeUpdate()
{
string url = "http://localhost:8275/api/GetVersion";
string latestVersion = null;
try
{
using (HttpClient client = new HttpClient())
{
Task<HttpResponseMessage> httpResponseMessage = client.GetAsync(url);
httpResponseMessage.Wait();
HttpResponseMessage response = httpResponseMessage.Result;
if (response.IsSuccessStatusCode)
{
Task<string> strings = response.Content.ReadAsStringAsync();
strings.Wait();
JObject jObject = JObject.Parse(strings.Result);
latestVersion = jObject["version"].ToString();
}
}
if (latestVersion != null)
{
var versioninfo = FileVersionInfo.GetVersionInfo(Application.ExecutablePath);
if (Version.Parse(latestVersion) > Version.Parse(versioninfo.FileVersion))
{
return true;
}
}
}
catch (Exception)
{
throw;
}
return false;
}
执行更新
public void UpdateApp()
{
string url = "http://localhost:8275/api/GetZips";
string zipName = "Update.zip";
string updateExeName = "Update.exe";
using (HttpClient client = new HttpClient())
{
Task<HttpResponseMessage> httpResponseMessage = client.GetAsync(url);
httpResponseMessage.Wait();
HttpResponseMessage response = httpResponseMessage.Result;
if (response.IsSuccessStatusCode)
{
Task<byte[]> bytes = response.Content.ReadAsByteArrayAsync();
bytes.Wait();
string path = AppDomain.CurrentDomain.BaseDirectory + "/" + zipName;
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
{
fs.Write(bytes.Result, 0, bytes.Result.Length);
}
}
Process process = new Process() { StartInfo = new ProcessStartInfo(updateExeName) };
process.Start();
Environment.Exit(0);
}
}
服务端
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.IO.Compression;
namespace WebApplication1.Controllers
{
[ApiController]
[Route("api")]
public class ClientUpdateController : ControllerBase
{
private readonly ILogger<ClientUpdateController> _logger;
public ClientUpdateController(ILogger<ClientUpdateController> logger)
{
_logger = logger;
}
/// <summary>
/// 获取版本号
/// </summary>
/// <returns>更新版本号</returns>
[HttpGet]
[Route("GetVersion")]
public IActionResult GetVersion()
{
string? res = null;
string zipfile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", "UpdateZip", "Update.zip");
string exeName = null;
using (ZipArchive archive = ZipFile.OpenRead(zipfile))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
//string filepath = Path.Combine(path, entry.FullName);
if (entry.FullName.EndsWith(".exe") && !entry.FullName.Equals("Update.exe"))
{
entry.ExtractToFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", "UpdateZip", entry.FullName), true);
exeName = entry.FullName;
}
}
}
FileVersionInfo versioninfo = FileVersionInfo.GetVersionInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", "UpdateZip", exeName));
res = versioninfo.FileVersion;
return Ok(new { version = res?.ToString() });
}
/// <summary>
/// 获取下载地址
/// </summary>
/// <returns>下载地址</returns>
[HttpGet]
[Route("GetUrl")]
public IActionResult GetUrl()
{
// var $"10.28.75.159:{PublicConfig.ServicePort}"
return Ok();
}
/// <summary>
/// 获取下载的Zip压缩包
/// </summary>
/// <returns>下载的Zip压缩包</returns>
[HttpGet]
[Route("GetZips")]
public async Task<IActionResult> GetZips()
{
// 创建一个内存流来存储压缩文件
using (var memoryStream = new MemoryStream())
{
// 构建 ZIP 文件的完整路径
var zipFilePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "UpdateZip", "Update.zip");
// 检查文件是否存在
if (!System.IO.File.Exists(zipFilePath))
{
return NotFound("The requested ZIP file does not exist.");
}
// 读取文件内容
var fileBytes = System.IO.File.ReadAllBytes(zipFilePath);
// 返回文件
return File(fileBytes, "application/zip", "Update.zip");
}
}
}
}
到此这篇关于C# winform实现自动更新的文章就介绍到这了,更多相关winform自动更新内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
