Re: file attributes: read creation and last access dates

[ Delphi Forum ] [ Delphi Tutorials -- by DelphiLand ]

Posted by webmaster Guido on September 08, 2003

In Reply to: Delphi: file attributes: read creation and last access dates posted by Stefan Loeners on September 07, 2003:

: How would I retrieve the CREATION date and the LAST ACCESS date of a given file?
: The function below reads the third date attribute, the date a file was LAST MODIFIED:
: function GetFileDateTime(FileName: string): TDateTime;
: var intFileAge: LongInt;
: begin
: intFileAge := FileAge(FileName);
: if intFileAge = -1 then
: Result := 0
: else
: Result := FileDateToDateTime(intFileAge)
: end;


Fat32 & NTFS are the only file systems that support creation and last access date/time, other file systems only support last modification date/time. Maybe that's why there are no functions to get the most recent access and update date/time, but we can calculate them using Delphi's FindFirst function.

FindFirst fills a TSearchRec record with info about a particular file. One of the fields of the TSearchRec is FindData.

Among other info, FindData has has 3 fields with date/time info of the file's creation, last access and last modification: ftCreationTime, ftLastAccessTime and ftLastWriteTime. These 3 fields are declared as TFileTime, a type that represents 64-bit dates in the Coordinated Universal Time format (UTC). To convert TFileTime to Delphi's TDateTime, you can use the following function:

function FileTimeToDTime(FTime: TFileTime): TDateTime;
  LocalFTime: TFileTime;
  STime: TSystemTime;
  FileTimeToLocalFileTime(FTime, LocalFTime);
  FileTimeToSystemTime(LocalFTime, STime);
  Result := SystemTimeToDateTime(STime);

Here's an example of how to show the creation, last access and last modification dates and times of a file:

procedure TForm1.Button1Click(Sender: TObject);
  SR: TSearchRec;
  CreateDT, AccessDT, ModifyDT: TDateTime;
  if FindFirst('c:\test\text01.txt', faAnyFile, SR) = 0 then begin
    CreateDT := FileTimeToDTime(SR.FindData.ftCreationTime);
    AccessDT := FileTimeToDTime(SR.FindData.ftLastAccessTime);;
    ModifyDT := FileTimeToDTime(SR.FindData.ftLastWriteTime);;
    ShowMessage('Created: ' + DateTimeToStr(CreateDT) +
      ' Accessed: ' + DateTimeToStr(AccessDT) +
      ' Modified: ' + DateTimeToStr(ModifyDT));
    ShowMessage('Sorry, could not find the file');

Related Articles and Replies:

[ Delphi Forum ]
[ DelphiLand: free Delphi source code, tips, tutorials ]