萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

WinForms 自動線上更新元件設計:版本檢查、下載、靜默安裝完整流程

架構概覽

WinForms 應用缺乏瀏覽器式的自動更新機制。本文實作一個 UpdateSoftwareForm,啟動時自動檢查伺服器 XML 版本資訊,發現新版本則下載安裝包、驗證、靜默安裝並重啟應用。

伺服器端版本資訊 XML 格式

<?xml version="1.0" encoding="utf-8"?>
<UpdateInfo>
  <Version>2.1.0.0</Version>
  <DownloadUrl>https://example.com/downloads/MyApp_v2.1.0.0.msi</DownloadUrl>
  <ForceUpdate>false</ForceUpdate>
  <Changelog>修正登入閃退、新增匯出 Excel 功能</Changelog>
</UpdateInfo>

客戶端核心流程

public partial class UpdateSoftwareForm : Form
{
    private readonly WebClient _client = new WebClient();
    private string _localVersion, _serverVersion, _downloadUrl;

    private async void UpdateSoftwareForm_Load(object sender, EventArgs e) {
        await CheckUpdateAsync();
    }

    private async Task CheckUpdateAsync() {
        try {
            // 1. 下載版本資訊 XML
            string xml = await _client.DownloadStringTaskAsync("https://example.com/UpdateInfo.xml");
            var doc = XDocument.Parse(xml);
            _serverVersion = doc.Root.Element("Version").Value;
            _downloadUrl = doc.Root.Element("DownloadUrl").Value;
            bool force = bool.Parse(doc.Root.Element("ForceUpdate").Value);

            // 2. 取得本地版本
            _localVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            // 3. 比較版本
            if (new Version(_serverVersion) > new Version(_localVersion)) {
                if (force || MessageBox.Show($"發現新版本 {_serverVersion},是否立即更新?", "更新提示", MessageBoxButtons.YesNo) == DialogResult.Yes) {
                    await DownloadAndInstallAsync();
                } else if (!force) {
                    Close(); // 使用者拒絕非強制更新,關閉更新視窗繼續使用舊版
                }
            } else {
                Close(); // 已是最新
            }
        } catch (Exception ex) {
            LogError(ex);
            Close();
        }
    }

    private async Task DownloadAndInstallAsync() {
        string installerPath = Path.Combine(Path.GetTempPath(), "MyApp_Update.msi");
        progressBar.Value = 10;

        // 下載安裝包(支援進度條)
        _client.DownloadProgressChanged += (s, e) => progressBar.Value = 10 + e.ProgressPercentage * 70 / 100;
        await _client.DownloadFileTaskAsync(_downloadUrl, installerPath);
        progressBar.Value = 85;

        // 靜默安裝 MSI
        var psi = new ProcessStartInfo("msiexec.exe", $"/i \"{installerPath}\" /qn /norestart")
        { UseShellExecute = false, CreateNoWindow = true };
        Process.Start(psi)?.WaitForExit();
        progressBar.Value = 100;

        // 重啟應用
        Application.Restart();
    }
}

關鍵技術細節

  • 版本比較:使用 Version 類別正確處理 1.2.10 > 1.2.9 邏輯,避免字串比較錯誤。
  • 非同步下載:DownloadFileTaskAsync + DownloadProgressChanged 更新 UI,不凍結介面。
  • 靜默安裝參數:msiexec /i pkg.msi /qn /norestart(無介面、不自動重啟)。
  • Application.Restart():自動關閉目前程序並啟動新版本。
  • 錯誤處理:網路失敗、XML 解析錯誤、安裝失敗均記錄日誌並優雅降級。

安全性加強建議

  1. 安裝包簽名驗證(Authenticode + SHA256 雜湊比對)。
  2. HTTPS 下載,防止中間人攻擊植入惡意程式。
  3. 伺服器端 XML 簽名或 HTTPS + 嚴格存取控制。
copyright © 萬盛學電腦網 all rights reserved