C# winform实现自动更新

 更新时间:2024年10月29日 08:38:04   作者:刘向荣  
这篇文章主要为大家详细介绍了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自动更新内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • C#实现更快读写超级大文件的方法详解

    C#实现更快读写超级大文件的方法详解

    这篇文章主要来和大家介绍一下C#实现更快读写超级大文件的方法,文中的示例代码简洁易懂,对我们深入了解C#有一定的帮助,快跟随小编一起学习起来吧
    2023-06-06
  • C# Razor语法规则

    C# Razor语法规则

    这篇文章介绍了C# Razor的语法规则,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-01-01
  • C#微信公众平台开发之access_token的获取存储与更新

    C#微信公众平台开发之access_token的获取存储与更新

    这篇文章主要介绍了C#微信公众平台开发之access_token的获取存储与更新的相关资料,需要的朋友可以参考下
    2016-03-03
  • 利用WCF双工模式实现即时通讯

    利用WCF双工模式实现即时通讯

    这篇文章主要介绍了利用WCF双工模式实现即时通讯的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-09-09
  • C#结构体特性实例分析

    C#结构体特性实例分析

    这篇文章主要介绍了C#结构体特性,以实例形式较为详细的分析了C#结构体的功能、定义及相关特性,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-09-09
  • C#的SQL操作类实例

    C#的SQL操作类实例

    这篇文章主要介绍了C#的SQL操作类实例,涉及到针对数据库的常用操作,在进行C#数据库程序设计中非常具有实用价值,需要的朋友可以参考下
    2014-10-10
  • 深入理解.NET中的异步

    深入理解.NET中的异步

    异步编程是程序设计的重点,在实际的项目,在大量的数据入库以及查询数据并进行计算的时候,程序的UI界面往往卡死在那里,这时候就需要对计算时间限制的过程进行异步处理,同时正确的使用异步编程去处理计算限制的操作和耗时IO操作还能提升的应用程序的吞吐量及性能
    2021-06-06
  • c#字符串使用正则表达式示例

    c#字符串使用正则表达式示例

    这篇文章主要介绍了c#字符串使用正则表达式示例,需要的朋友可以参考下
    2014-02-02
  • C#生成互不相同随机数的实现方法

    C#生成互不相同随机数的实现方法

    这篇文章主要介绍了C#生成互不相同随机数的实现方法,文中详细描述了C#生成互不相同随机数的各个步骤及所用到的函数,非常具有借鉴价值,需要的朋友可以参考下
    2014-09-09
  • C#获取ListView鼠标下的Item实例

    C#获取ListView鼠标下的Item实例

    下面小编就为大家带来一篇C#获取ListView鼠标下的Item实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-01-01

最新评论