SoFunction
Updated on 2025-03-03

C# winform realizes automatic update

1. Check the current program and the latest program version of the server. If it is lower than the server, then you can upgrade it.

2. Server-side file packaging.zip file

3. Unzip the compressed package file and replace all files under the client's debug.

4. Create another program to understand the compression overwrites the original lower version of the client program.

There is a project Update that is responsible for copying and decompressing the folder after it should be closed and complete the update

Here you select the winform project, the project name Update

The following isUpdate/Contents of the file:

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;

namespace Update
{
    internal static class Program
    {
        private static readonly HashSet<string> selfFiles = new HashSet<string> { "", "", "" };

        [STAThread]
        static void Main()
        {
            string delay = ["delay"];

            ((delay));

            string exePath = null;
            string path = ;
            string zipfile = (path, "");

            try
            {
                using (ZipArchive archive = (zipfile))
                {
                    foreach (ZipArchiveEntry entry in )
                    {
                        if (())
                        {
                            continue;
                        }

                        string filepath = (path, );

                        if ((".exe"))
                        {
                            exePath = filepath;
                        }
                        (filepath, true);
                    }
                }
            }
            catch (Exception ex)
            {
                ("Upgrade failed" + );
                throw;
            }

            if ((zipfile))
                (zipfile);

            if (exePath == null)
            {
                ("The executable file cannot be found!");
                return;
            }

            Process process = new Process();
             = new ProcessStartInfo(exePath);
            ();
        }

    }
}

The following isContents of the file:

<?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 application

Software version

[assembly: AssemblyFileVersion("1.0.0.0")]

if (JudgeUpdate())
{
    UpdateApp();
}

Check for updates

private bool JudgeUpdate()
{
    string url = "http://localhost:8275/api/GetVersion";

    string latestVersion = null;
    try
    {
        using (HttpClient client = new HttpClient())
        {
            Task<HttpResponseMessage> httpResponseMessage = (url);
            ();

            HttpResponseMessage response = ;
            if ()
            {
                Task<string> strings = ();
                ();

                JObject jObject = ();
                latestVersion = jObject["version"].ToString();

            }
        }

        if (latestVersion != null)
        {
            var versioninfo = ();
            if ((latestVersion) > ())
            {
                return true;
            }
        }
    }
    catch (Exception)
    {
        throw;
    }
    return false;
}

Perform updates

public void UpdateApp()
{
    string url = "http://localhost:8275/api/GetZips";
    string zipName = "";
    string updateExeName = "";

    using (HttpClient client = new HttpClient())
    {
        Task<HttpResponseMessage> httpResponseMessage = (url);
        ();

        HttpResponseMessage response = ;
        if ()
        {
            Task<byte[]> bytes = ();
            ();

            string path =  + "/" + zipName;

            using (FileStream fs = new FileStream(path, , ))
            {
                (, 0, );
            }
        }

        Process process = new Process() { StartInfo = new ProcessStartInfo(updateExeName) };
        ();
        (0);
    }
}

Server side

using ;
using ;
using ;

namespace 
{
    [ApiController]
    [Route("api")]
    public class ClientUpdateController : ControllerBase
    {

        private readonly ILogger&lt;ClientUpdateController&gt; _logger;

        public ClientUpdateController(ILogger&lt;ClientUpdateController&gt; logger)
        {
            _logger = logger;
        }

        /// &lt;summary&gt;
        /// Get the version number        /// &lt;/summary&gt;
        /// <returns>Update version number</returns>        [HttpGet]
        [Route("GetVersion")]
        public IActionResult GetVersion()
        {
            string? res = null;
            string zipfile = (, "wwwroot", "UpdateZip", "");
            string exeName = null;

            using (ZipArchive archive = (zipfile))
            {
                foreach (ZipArchiveEntry entry in )
                {
                    //string filepath = (path, );

                    if ((".exe") &amp;&amp; !(""))
                    {
                        ((, "wwwroot", "UpdateZip", ), true);
                        exeName = ;
                    }
                }
            }

            FileVersionInfo versioninfo = ((, "wwwroot", "UpdateZip", exeName));
            res = ;

            return Ok(new { version = res?.ToString() });
        }

        /// &lt;summary&gt;
        /// Get the download address        /// &lt;/summary&gt;
        /// <returns>Download Address</returns>        [HttpGet]
        [Route("GetUrl")]
        public IActionResult GetUrl()
        {
            // var $"10.28.75.159:{}"
            return Ok();
        }


        /// &lt;summary&gt;
        /// Get the downloaded Zip compressed package        /// &lt;/summary&gt;
        /// <returns>Downloaded Zip Compression Pack</returns>        [HttpGet]
        [Route("GetZips")]
        public async Task&lt;IActionResult&gt; GetZips()
        {
            // Create a memory stream to store compressed files            using (var memoryStream = new MemoryStream())
            {
                // The complete path to build the ZIP file                var zipFilePath = ((), "wwwroot", "UpdateZip", "");
                // Check whether the file exists                if (!(zipFilePath))
                {
                    return NotFound("The requested ZIP file does not exist.");
                }
                // Read file content                var fileBytes = (zipFilePath);
                // Return to file                return File(fileBytes, "application/zip", "");
            }
        }

    }
}

This is the end of this article about C# winform automatic update. For more related content on automatic update of winform, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!