欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C# winform實現(xiàn)自動更新

 更新時間:2024年10月29日 08:38:04   作者:劉向榮  
這篇文章主要為大家詳細(xì)介紹了C# winform實現(xiàn)自動更新的相關(guān)知識,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

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#實現(xiàn)更快讀寫超級大文件的方法詳解

    C#實現(xiàn)更快讀寫超級大文件的方法詳解

    這篇文章主要來和大家介紹一下C#實現(xiàn)更快讀寫超級大文件的方法,文中的示例代碼簡潔易懂,對我們深入了解C#有一定的幫助,快跟隨小編一起學(xué)習(xí)起來吧
    2023-06-06
  • C#?Razor語法規(guī)則

    C#?Razor語法規(guī)則

    這篇文章介紹了C#?Razor的語法規(guī)則,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-01-01
  • C#微信公眾平臺開發(fā)之a(chǎn)ccess_token的獲取存儲與更新

    C#微信公眾平臺開發(fā)之a(chǎn)ccess_token的獲取存儲與更新

    這篇文章主要介紹了C#微信公眾平臺開發(fā)之a(chǎn)ccess_token的獲取存儲與更新的相關(guān)資料,需要的朋友可以參考下
    2016-03-03
  • 利用WCF雙工模式實現(xiàn)即時通訊

    利用WCF雙工模式實現(xiàn)即時通訊

    這篇文章主要介紹了利用WCF雙工模式實現(xiàn)即時通訊的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-09-09
  • C#結(jié)構(gòu)體特性實例分析

    C#結(jié)構(gòu)體特性實例分析

    這篇文章主要介紹了C#結(jié)構(gòu)體特性,以實例形式較為詳細(xì)的分析了C#結(jié)構(gòu)體的功能、定義及相關(guān)特性,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-09-09
  • C#的SQL操作類實例

    C#的SQL操作類實例

    這篇文章主要介紹了C#的SQL操作類實例,涉及到針對數(shù)據(jù)庫的常用操作,在進行C#數(shù)據(jù)庫程序設(shè)計中非常具有實用價值,需要的朋友可以參考下
    2014-10-10
  • 深入理解.NET中的異步

    深入理解.NET中的異步

    異步編程是程序設(shè)計的重點,在實際的項目,在大量的數(shù)據(jù)入庫以及查詢數(shù)據(jù)并進行計算的時候,程序的UI界面往往卡死在那里,這時候就需要對計算時間限制的過程進行異步處理,同時正確的使用異步編程去處理計算限制的操作和耗時IO操作還能提升的應(yīng)用程序的吞吐量及性能
    2021-06-06
  • c#字符串使用正則表達(dá)式示例

    c#字符串使用正則表達(dá)式示例

    這篇文章主要介紹了c#字符串使用正則表達(dá)式示例,需要的朋友可以參考下
    2014-02-02
  • C#生成互不相同隨機數(shù)的實現(xiàn)方法

    C#生成互不相同隨機數(shù)的實現(xiàn)方法

    這篇文章主要介紹了C#生成互不相同隨機數(shù)的實現(xiàn)方法,文中詳細(xì)描述了C#生成互不相同隨機數(shù)的各個步驟及所用到的函數(shù),非常具有借鑒價值,需要的朋友可以參考下
    2014-09-09
  • C#獲取ListView鼠標(biāo)下的Item實例

    C#獲取ListView鼠標(biāo)下的Item實例

    下面小編就為大家?guī)硪黄狢#獲取ListView鼠標(biāo)下的Item實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-01-01

最新評論