首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 客戶端自動更新元件設計與實作

     編輯:關於C#

軟體部署後的版本更新一直是桌面應用開發的痛點。本文介紹一個輕量級、配置驅動的自動更新元件,支援多備援下載網址、斷點續傳邏輯與更新後自動啟動主程式。

架構設計

核心流程:

  1. 讀取本地 autoupdate.config 取得更新伺服器清單
  2. 依序嘗試各 URL 直到取得有效回應
  3. 解析回應內容獲取檔案下載清單(格式:遠端URL$本地檔名)
  4. 逐一下載檔案至對應目錄
  5. 執行配置的啟動指令(如 cmd.exe 或主程式路徑)

配置檔格式

autoupdate.config:

url=https://server1/update.xml$https://server2/update.xml$https://backup/update.xml
cmd=MyApp.exe

更新清單回應格式(每行一筆):

https://server/files/v2.1/core.dll$core.dll
https://server/files/v2.1/ui.resources$resources/ui.resources
https://server/files/v2.1/patch.sql$scripts/patch.sql

關鍵實作細節

多 URL 容錯機制

string[] urls = configUrl.Split('$');
foreach (string url in urls) {
    try {
        string response = DownloadString(url);
        if (!string.IsNullOrEmpty(response)) {
            ParseAndDownloadFiles(response);
            return true;
        }
    } catch (Exception ex) {
        LogError($"URL {url} 失敗: {ex.Message}");
        continue; // 嘗試下一個
    }
}
return false;

檔案下載與目錄建立

foreach (string line in fileList) {
    string[] parts = line.Split('$');
    string remoteUrl = parts[0];
    string localPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, parts[1]);
    
    Directory.CreateDirectory(Path.GetDirectoryName(localPath));
    using (WebClient wc = new WebClient()) {
        wc.DownloadFile(remoteUrl, localPath);
    }
}

錯誤記錄與回滾

更新過程若發生例外,自動寫入 autoupdate.error 記錄錯誤詳情,方便診斷:

catch (Exception ex) {
    File.WriteAllText("autoupdate.error", 
        $"{DateTime.Now}: {ex.Message}\n{ex.StackTrace}");
    throw;
}

部署建議

  • 將更新程式 (AutoUpdater.exe) 與主程式放在同一目錄
  • 主程式啟動時檢查更新參數,若需更新則啟動 AutoUpdater 並自我結束
  • 更新伺服器端只需靜態檔案伺服器,無需複雜後端
  • 支援 HTTPS 與基本認證,適應企業內網環境

自動更新程式執行介面

解壓後檔案結構:AutoUpdater.exe、autoupdate.config

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved