C# winform實現(xiàn)自動更新
1.檢查當(dāng)前的程序和服務(wù)器的最新程序的版本,如果低于服務(wù)端的那么才能升級
2.服務(wù)端的文件打包.zip文件
3.把壓縮包文件解壓縮并替換客戶端的debug下所有文件。
4.創(chuàng)建另外的程序為了解壓縮覆蓋掉原始的低版本的客戶程序。
有個項目Update 負(fù)責(zé)在應(yīng)該關(guān)閉之后復(fù)制解壓文件夾 完成更新
這里選擇winform項目,項目名Update
以下是 Update/Program.cs
文件的內(nèi)容:
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("找不到可執(zhí)行文件!"); return; } Process process = new Process(); process.StartInfo = new ProcessStartInfo(exePath); process.Start(); } } }
以下是 App.config
文件的內(nèi)容:
<?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應(yīng)用
軟件版本
[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; }
執(zhí)行更新
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); } }
服務(wù)端
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() { // 創(chuàng)建一個內(nèi)存流來存儲壓縮文件 using (var memoryStream = new MemoryStream()) { // 構(gòu)建 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."); } // 讀取文件內(nèi)容 var fileBytes = System.IO.File.ReadAllBytes(zipFilePath); // 返回文件 return File(fileBytes, "application/zip", "Update.zip"); } } } }
到此這篇關(guān)于C# winform實現(xiàn)自動更新的文章就介紹到這了,更多相關(guān)winform自動更新內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#微信公眾平臺開發(fā)之a(chǎn)ccess_token的獲取存儲與更新
這篇文章主要介紹了C#微信公眾平臺開發(fā)之a(chǎn)ccess_token的獲取存儲與更新的相關(guān)資料,需要的朋友可以參考下2016-03-03