C# winform實(shí)現(xiàn)自動(dòng)更新
1.檢查當(dāng)前的程序和服務(wù)器的最新程序的版本,如果低于服務(wù)端的那么才能升級(jí)
2.服務(wù)端的文件打包.zip文件
3.把壓縮包文件解壓縮并替換客戶端的debug下所有文件。
4.創(chuàng)建另外的程序?yàn)榱私鈮嚎s覆蓋掉原始的低版本的客戶程序。
有個(gè)項(xiàng)目Update 負(fù)責(zé)在應(yīng)該關(guān)閉之后復(fù)制解壓文件夾 完成更新
這里選擇winform項(xiàng)目,項(xiàng)目名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("升級(jí)失敗" + 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> /// 獲取版本號(hào) /// </summary> /// <returns>更新版本號(hào)</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)建一個(gè)內(nèi)存流來(lái)存儲(chǔ)壓縮文件 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實(shí)現(xiàn)自動(dòng)更新的文章就介紹到這了,更多相關(guān)winform自動(dòng)更新內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實(shí)現(xiàn)更快讀寫超級(jí)大文件的方法詳解
這篇文章主要來(lái)和大家介紹一下C#實(shí)現(xiàn)更快讀寫超級(jí)大文件的方法,文中的示例代碼簡(jiǎn)潔易懂,對(duì)我們深入了解C#有一定的幫助,快跟隨小編一起學(xué)習(xí)起來(lái)吧2023-06-06C#微信公眾平臺(tái)開(kāi)發(fā)之a(chǎn)ccess_token的獲取存儲(chǔ)與更新
這篇文章主要介紹了C#微信公眾平臺(tái)開(kāi)發(fā)之a(chǎn)ccess_token的獲取存儲(chǔ)與更新的相關(guān)資料,需要的朋友可以參考下2016-03-03利用WCF雙工模式實(shí)現(xiàn)即時(shí)通訊
這篇文章主要介紹了利用WCF雙工模式實(shí)現(xiàn)即時(shí)通訊的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-09-09C#生成互不相同隨機(jī)數(shù)的實(shí)現(xiàn)方法
這篇文章主要介紹了C#生成互不相同隨機(jī)數(shù)的實(shí)現(xiàn)方法,文中詳細(xì)描述了C#生成互不相同隨機(jī)數(shù)的各個(gè)步驟及所用到的函數(shù),非常具有借鑒價(jià)值,需要的朋友可以參考下2014-09-09C#獲取ListView鼠標(biāo)下的Item實(shí)例
下面小編就為大家?guī)?lái)一篇C#獲取ListView鼠標(biāo)下的Item實(shí)例。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-01-01