Home Backend Development C#.Net Tutorial Example analysis of how to automatically update local programs in C#

Example analysis of how to automatically update local programs in C#

Aug 08, 2017 pm 02:13 PM
.net local

About automatic updates of the system. Recently, there has been a situation where it is necessary to overwrite the local client with the latest version of the system files in the Java backend, which is referred to as automatic update.

The local system will obtain the version number of the current system to request the interface data of the background java. What is returned to me is the base64 byte stream converted from the background compression package.

The client needs to update the local program to get the new version.


    if (UpdateSystem(Path.Combine(Application.StartupPath, "Version.txt"), Path.Combine(Application.StartupPath, "u.zip")))
            {
                Application.Exit();
            }
Copy after login


/// <summary>
        /// 读取本地版本请求更新
        /// </summary>
        /// <param name="document">读取的文件信息</param>
        /// <param name="zipPath">返回zip包本地路径</param>
        /// <returns></returns>
        private bool UpdateSystem(string document, string zipPath)
        {
            try
            {
                Dictionary<string, string> postDic = new Dictionary<string, string>();
                //获取文件内的版本号
                if(File.Exists(document))
                {
                    postDic.Add("version", File.ReadAllText(document).Trim());
                }
                else
                {
                    postDic.Add("version", "0");
                }

                string postJson = JsonConvert.SerializeObject(postDic);
                string url = GetAppSettingValue("serverUrl") + "parkClient/parkClientUpdate";
                //返回的json数据
                JObject obj = (JObject)JsonConvert.DeserializeObject(PostData(postJson, url));
                string newVersion = obj["version"].ToString();
                if (!String.IsNullOrWhiteSpace(newVersion))
                {
                    byte[] bytesFile = Convert.FromBase64String(obj["byteArray"].ToString());
                    if (obj["clientMD5"].ToString() == BitConverter.ToString(
                        new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(bytesFile)).Replace("-", ""))
                    {
                        ZipCoverage(bytesFile, zipPath);

                        File.WriteAllText(document, newVersion);
                       
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 解压zip包覆盖更新
        /// </summary>
        /// <param name="bytes">接受更新包的字节信息</param>
        /// <param name="zpath">覆盖的路径</param>
        private void ZipCoverage(byte[] bytes, string zpath)
        {
            File.WriteAllBytes(zpath, bytes);
            using (ZipArchive archive = ZipFile.OpenRead(zpath))
            {
                string file = null;
                foreach (ZipArchiveEntry entry in archive.Entries)
                {
                    if (!entry.FullName.EndsWith("/"))
                    {
                        file = Path.Combine(Application.StartupPath, entry.FullName);
                        if (File.Exists(file))
                        {
                            File.Delete(file);
                        }
                    }
                }
            }
            ZipFile.ExtractToDirectory(zpath, Application.StartupPath);
           
        }

        /// <summary>
        /// 获取配置文件中的appSettings节中的配置内容
        /// </summary>
        /// <param name="appSettingKey"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private string GetAppSettingValue(string appSettingKey)
        {
            ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = @"TDH.Parking.Client.exe.config" };
            return ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None).AppSettings.Settings[appSettingKey].Value;
        }
Copy after login


byte[] bytesFile = Convert.FromBase64String(obj["byteArray"].ToString());
Copy after login

Here is the byte stream obtained .

This method can solve the problem that multiple projects in the same solution can read the App.config under the same project. document.

Note: There are referenced class libraries, which are used to operate compressed packages.

Let’s talk about the idea: The first step is actually to get the byte stream of the compressed package and save it locally. The second step is to loop through the files of the compressed package and replace the local files to complete the version update of the local system. .

No matter simple or complex, we need to move forward step by step.

The above is the detailed content of Example analysis of how to automatically update local programs in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to add local music to soda music How to add local music to soda music Feb 23, 2024 pm 07:13 PM

How to add local music to Soda Music? You can add your favorite local music to Soda Music APP, but most friends don’t know how to add local music. Next is the graphic tutorial on how to add local music to Soda Music brought by the editor. , interested users come and take a look! Tutorial on using soda music. How to add local music to soda music. 1. First open the soda music APP and click on the [Music] function area at the bottom of the main page; 2. Then enter the play page and click the [three dots] icon in the lower right corner; 3. Finally Expand the function bar below and select the [Download] button to add it to local music.

What are the employment prospects of C#? What are the employment prospects of C#? Oct 19, 2023 am 11:02 AM

Whether you are a beginner or an experienced professional, mastering C# will pave the way for your career.

How to add watermark and save remote images after saving them locally in PHP? How to add watermark and save remote images after saving them locally in PHP? Jul 11, 2023 pm 11:48 PM

How to add watermark and save remote images after saving them locally in PHP? In PHP development, we often encounter the need to save remote images locally. Sometimes, we may also need to add a watermark to the saved image to protect copyright or add additional information. This article will introduce how to use PHP to save remote pictures to local and add watermarks to the saved pictures. 1. Save remote images to local. First, we need to use PHP's file operation function to save remote images to local. Here is a simple example code: &

Share several .NET open source AI and LLM related project frameworks Share several .NET open source AI and LLM related project frameworks May 06, 2024 pm 04:43 PM

The development of artificial intelligence (AI) technologies is in full swing today, and they have shown great potential and influence in various fields. Today Dayao will share with you 4 .NET open source AI model LLM related project frameworks, hoping to provide you with some reference. https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel is an open source software development kit (SDK) designed to integrate large language models (LLM) such as OpenAI, Azure

Win11 apk installation guide Win11 apk installation guide Jan 03, 2024 pm 10:24 PM

As we all know, Microsoft announced that win11 will be able to run Android applications and install local apk. However, after updating win11, users found that they did not know how to install the local apk. In fact, this is because Microsoft has not yet implemented this feature for win11. It is necessary Wait for the function to be installed before you can use it. How to install local apk in win11: 1. According to Microsoft, after win11 has installed this function, you can directly double-click the downloaded apk file to install it directly. 2. After the installation is completed, users can also run it directly in the system. 3. Although it is now the official version of win11, Microsoft has not yet implemented this feature for win11. 4. So if the user wants to use win11

.NET performance optimization technology for developers .NET performance optimization technology for developers Sep 12, 2023 am 10:43 AM

If you are a .NET developer, you must be aware of the importance of optimizing functionality and performance in delivering high-quality software. By making expert use of the provided resources and reducing website load times, you not only create a pleasant experience for your users but also reduce infrastructure costs.

Performance differences between Java framework and .NET framework Performance differences between Java framework and .NET framework Jun 03, 2024 am 09:19 AM

In terms of high-concurrency request processing, .NETASP.NETCoreWebAPI performs better than JavaSpringMVC. The reasons include: AOT early compilation, which reduces startup time; more refined memory management, where developers are responsible for allocating and releasing object memory.

How to add local loopback address on CentOS7? How to add local loopback address on CentOS7? Jan 13, 2024 pm 08:00 PM

1. Temporarily add ipaddradd10.10.1.1/32devlo:1 and fail after restarting. 2. Permanently add cd/etc/sysconfig/network-scriptscpifcfg-loifcfg-lo:1[root@localhostnetwork-scripts]#catifcfg-lo:1DEVICE=lo: 1IPADDR=10.10.1.1NETMASK=255.255.255.255ONBOOT=yesNAME=loopback1[root@localhostnetwork-scripts]#ipa

See all articles