delphi獲取檔案的建立/修改時間、按時間刪除指定檔案下的檔案
阿新 • • 發佈:2021-11-22
uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,DateUtils; ... //獲取檔案的建立時間 function GetFileCreationTime(const FileName: String): TDateTime; var FileTime: TFileTime; LocalFileTime: TFileTime; hFile: THandle; SystemTime: TSystemTime; begin Result :好的程式碼像粥一樣,都是用時間熬出來的= 0; FileTime.dwLowDateTime := 0; FileTime.dwHighDateTime := 0; hFile := FileOpen(FileName, fmShareDenyNone); try if hFile <> 0 then begin Windows.GetFileTime(hFile, @FileTime, nil, nil); FileTimeToLocalFileTime(FileTime, LocalFileTime); FileTime := LocalFileTime;end; finally FileClose(hFile); end; if FileTimeToSystemTime(FileTime, SystemTime) then Result := SystemTimeToDateTime(SystemTime); end; //獲取檔案的修改時間 function GetFileEditTime(const FileName: String): TDateTime; var FileTime: TFileTime; LocalFileTime: TFileTime; hFile: THandle; SystemTime: TSystemTime;begin Result := 0; FileTime.dwLowDateTime := 0; FileTime.dwHighDateTime := 0; hFile := FileOpen(FileName, fmShareDenyNone); try if hFile <> 0 then begin Windows.GetFileTime(hFile, nil, nil, @FileTime); FileTimeToLocalFileTime(FileTime, LocalFileTime); FileTime := LocalFileTime; end; finally FileClose(hFile); end; if FileTimeToSystemTime(FileTime, SystemTime) then Result := SystemTimeToDateTime(SystemTime); end; 呼叫: edit1.text:=datetimetostr( GetFileEditTime('E:\test\D12000398C1.csv')); 獲取資料夾下的所有檔名稱、按檔案的修改時間刪除指定的檔案 procedure TForm1.Button2Click(Sender: TObject); var r:TsearchRec; filelist:Tstringlist; i:integer; begin filelist:=Tstringlist.create; if findfirst('e:\test\'+'*.csv',faanyfile,r)=0 then filelist.add(r.name); while findnext(r)=0 do filelist.add(r.name); findclose(r); //這樣filelist中就儲存了你輸入的資料夾下的所有檔案,我下面顯示在一個memo元件中了 for i:=0 to filelist.count-1 do begin if hoursBetween(GetFileEditTime('E:\test\'+filelist[i]),Now)>48 then begin try deletefile('E:\test\'+filelist[i]); except end; end; //memo1.lines.text:=memo1.lines.text+filelist[i]+#13; end; filelist.free; end;