【C#】WinForm 升级篇

Winform,C#/.NET 2019-12-17

  1. 流程描述

微信截图_20191217114450.png

2.升级配置结构

{
  "err_code": 200,
  "err_msg": "success",
  "version": "2.1.2",
  "download_url": "http://******/upgrade_package/Upgrade2.1.2.zip",
  "fingerprint": "d5af2da283ed4da97dbb1e445620669f"
}

3.参考资料

https://download.csdn.net/download/qq592691117/10623907

4.参考程序修正 主要问题:没有使用线程,从而升级过程界面会假死。 使用线程方式,将过程放入 Upgrade() 方法中,在线程中调用,有点小优雅吧。

private void StartUpgrade()
{
    Thread thread = new Thread(new ThreadStart(() => {
        try
        {
            Upgrade();
            // writeLog("更新成功!");
            ShowTip("更新成功!", Colors.Green);
        }
        catch (Exception ex)
        {
            common.log.LogTextHelper.WriteLine(ex.Message);
            ShowTip(ex.Message, Colors.Red);
        }
        finally
        {
            DeleteFile();
        }

        Thread.Sleep(3000);
        this.Dispatcher.Invoke(new Action(() =>
        {
            this.Close();
        }));
    }));

    thread.Start();
}

进度条UI的更新(调用此方法在线程中更新)

private void AddPercent()
{
    this.Dispatcher.Invoke(new Action(() =>
    {
        pgbUpdate.Value++;
    }));
}

不允许同时打开多次(在App.xaml.cs中)

public partial class App : Application
{
    System.Threading.Mutex mutex;
    //重写OnStartup,获得启动程序  
    protected override void OnStartup(StartupEventArgs e)
    {
        bool ret;
        mutex = new System.Threading.Mutex(true, "AutoUpdate", out ret);
        if (!ret) // 不可多次打开
        { 
            Environment.Exit(0);
        }
        else
        {
            if (e.Args != null && e.Args.Count() > 0)
            {
                var lastVersion = e.Args[0];  // 取得传递的版本号
            }
            base.OnStartup(e);
        }
    }
}

5.其它 指纹验证 取得文件的 MD5 值

public class FileHelper
{
    static public string GetMD5WithFilePath(string filePath)
    {
        using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] hash_byte = md5.ComputeHash(file);
            string str = System.BitConverter.ToString(hash_byte);
            str = str.Replace("-", "").ToLower();
            return str;
        }
    }
}

在线程中更新文本显示(支持指定颜色,如 Colors.Red)

private void ShowTip(string tip, Color color)
{
    this.Dispatcher.Invoke(new Action(() =>
    {
        lbl_name.Foreground = new SolidColorBrush(color);
        lbl_name.Content = tip;
    }));
}

帅气的楼主关闭了评论