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

黄舟
Release: 2017-08-08 14:13:15
Original
2411 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template