所以我有一個“下載”檔案夾,我把我下載的所有東西都放在我的日常作業中。你知道我們總是自動化一切,所以我試圖構建一個簡單的應用程式來每天運行以洗掉超過 30 天的檔案,因為我必須不時手動執行此操作以避免檔案夾變得太大。
這是我的代碼:
function TForm1.deleteOldDownloads: boolean;
var
f: string;
i, d: Integer;
var
sl: tstringlist;
begin
try
FileListBox1.Directory := '\\psf\home\downloads';
FileListBox1.refresh;
sl := tstringlist.create;
for i := 0 to FileListBox1.items.count - 1 do
begin
f := FileListBox1.Directory '\' FileListBox1.items[i];
if fileexists(f) then
d := daysbetween(FileAge(f), now)
else
d := 0;
if d > 30 then // problem is here, d is always a big number, not the actually age of file
sl.Add(f);
end;
if sl.count > 0 then
begin
for i := 0 to sl.count do
begin
f := sl[i];
deletefile(f);
end;
end;
sl.Free;
except
on e: Exception do
begin
end;
end;
問題是“d”變數回傳非常大的數字,如 1397401677,即使檔案只有 1 天。
這里唯一的細節是我在 Parallels 虛擬機中運行 Windows,并且“\psf\home\downloads”檔案夾在 Mac 上,但我可以使用 Windows 資源管理器正常訪問此檔案夾,因此對于 Delphi 來說就像一個常規的本地檔案夾。
我錯過了什么?
uj5u.com熱心網友回復:
你閱讀檔案的FileAge?在編程學校的第一天,你會學到“當你開始使用一個新的函式或 API 時,你首先要閱讀它的檔案”。在這種情況下,函式的檔案說
FileAge不推薦使用[one-argument] 多載版本。
所以你正在使用一個你不應該使用的函式。
盡管如此,這個功能應該仍然有效。
但是你期望它回傳什么?好吧,顯然檔案說它應該回傳的內容:
第一個多載回傳一個整數,表示檔案的作業系統時間戳。稍后可以
TDateTime使用該FileDateToDateTime函式將結果轉換為 a 。
但是當您在 in 中使用它時DaysBetween,您會認為它已經是一個TDateTime!
為什么 FileAge 回傳意外值?
不是。它可能正在回傳其檔案所說的應該回傳的內容。
uj5u.com熱心網友回復:
您使用的舊版本FileAge()以 DOS 數字格式回傳時間戳,但您將其視為TDateTime,而事實并非如此。正如FileAge檔案所說:
第一個多載回傳一個整數,表示檔案的作業系統時間戳。稍后可以
TDateTime使用該FileDateToDateTime()函式將結果轉換為 a 。
所以,按照檔案說的去做,例如:
var
age: Integer;
age := FileAge(f);
if age <> -1 then
d := DaysBetween(FileDateToDateTime(age), Now)
否則,使用該FileAge()輸出 a的較新版本TDateTime開始,例如:
var
dt: TDateTime;
if FileAge(f, dt) then
d := DaysBetween(dt, Now)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315588.html
下一篇:Firedac將列名作為引數傳遞
