WinForms 應用缺乏瀏覽器式的自動更新機制。本文實作一個 UpdateSoftwareForm,啟動時自動檢查伺服器 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(無介面、不自動重啟)。