开发者

C# winform实现自动更新

目录
  • 有个项目Update 负责在应该关闭之后复制解压文件夹 完成更新
  • 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 HashSetandroid<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, "Upythonpdate.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(), "wwwroojst", "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自动更新内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

    0

    上一篇:

    下一篇:

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    最新开发

    开发排行榜