現代軟體幾乎都具備「啟動時檢查更新、自動下載替換」的能力。本文示範如何在 Delphi 中利用 TNMHTTP (Indy 9/10 同理) 實作完整的線上更新流程:讀取伺服器版本資訊、比對本地檔案時間、下載新檔、備份舊檔並替換。
伺服器提供 update.htm (實際為 INI 格式),記錄各檔案的最後修改時間:
[program1.exe]
datetime=2003-07-06
[program1.hlp]
datetime=2003-07-06
客戶端下載後另存為 update.ini,利用 TIniFile 解析。
function ExistNewFile: Boolean;
var
i, iFileHandle: Integer;
FileDateTime: TDateTime;
AppIni: TIniFile;
g_path, url: string;
files: TStrings;
begin
Result := False;
url := 'https://bianceng.cn/update.htm/';
g_path := ExtractFilePath(Application.ExeName);
if g_path[Length(g_path)] <> '\' then g_path := g_path + '\';
if url[Length(url)] <> '/' then url := url + '/';
// 1. 下載更新資訊檔
try
HTTPFiles.InputFileMode := True;
HTTPFiles.OutputFileMode := False;
HTTPFiles.ReportLevel := Status_Basic;
HTTPFiles.Body := g_path + 'update\update.ini';
HTTPFiles.Get(url);
except
Exit; // 下載失敗視為無更新
end;
// 2. 解析並比對時間
files := TStringList.Create;
AppIni := TIniFile.Create(g_path + '\update\update.ini');
try
AppIni.ReadSections(files); // 取得所有區段名稱 (即檔名)
for i := 0 to files.Count - 1 do
begin
iFileHandle := FileOpen(g_path + files[i], fmShareDenyNone);
if iFileHandle <> -1 then
begin
FileDateTime := FileDateToDateTime(FileGetDate(iFileHandle));
FileClose(iFileHandle);
// 本地時間 < 伺服器時間 表示有新版
if FileDateTime < StrToDateTime(AppIni.ReadString(files[i], 'datetime', '1900-1-1')) then
begin
Result := True;
Break;
end;
end;
end;
finally
AppIni.Free;
files.Free;
end;
end;
// 下載需更新的檔案至 update 子目錄
for i := 0 to files.Count - 1 do
begin
HTTPFiles.Body := g_path + 'update\' + files[i];
HTTPFiles.Get(url + files[i]);
end;
// 備份原檔 (*.bak) 並複製新檔覆蓋
for i := 0 to files.Count - 1 do
CopyFile(PChar(g_path + files[i]), PChar(g_path + files[i] + '.bak'), False);
for i := 0 to files.Count - 1 do
CopyFile(PChar(g_path + 'update\' + files[i]), PChar(g_path + files[i]), False);
TNMHTTP 的 OnPacketRecvd 事件可計算下載進度,更新進度條。線上更新的核心在於「版本資訊發佈 → 客戶端輪詢比對 → 差異下載 → 安全替換」。本文提供最精簡的實作骨架,開發者可據此擴充斷點續傳、靜默安裝、簽章驗證等企業級功能。