2004. május 12., szerda

Get File Created, Modified and Accessed dates


Problem/Question/Abstract:

How to get File Created, Modified and Accessed dates

Answer:

This function will return Created,Modified and Accessed datetimes of a given file. The datetimes are returned as TDateTime variables passed by REFERENCE. The function returns true if the file was found, else false. The dates are the same as displayed by EXPLORER when file properties is selected

// ================================================================
// Return the three dates (Created,Modified,Accessed
// of a given filename. Returns FALSE if file cannot
// be found or permissions denied. Results are returned
// in TdateTime OUT parameters
// ================================================================

function GetFileTimes(FileName: string;
  out Created: TDateTime;
  out Modified: TDateTime;
  out Accessed: TDateTime): boolean;
var
  FileHandle: integer;
  Cmd: boolean;
  FTimeC, FTimeA, FTimeM: TFileTime;
  LTime: TFileTime;
  STime: TSystemTime;
begin
  FileHandle := FileOpen(FileName, fmShareDenyNone);
  Created := 0.0;
  Modified := 0.0;
  Accessed := 0.0;

  if FileHandle < 0 then
    Cmd := false
  else
  begin
    Cmd := true;
    GetFileTime(FileHandle, @FTimeC, @FTimeA, @FTimeM);
    FileClose(FileHandle);

    // Created
    FileTimeToLocalFileTime(FTimeC, LTime);
    if FileTimeToSystemTime(LTime, STime) then
    begin
      Created := EncodeDate(STime.wYear, STime.wMonth, STime.wDay);
      Created := Created + EncodeTime(STime.wHour, STime.wMinute, STime.wSecond,
        STime.wMilliSeconds);
    end;

    // Accessed
    FileTimeToLocalFileTime(FTimeA, LTime);
    if FileTimeToSystemTime(LTime, STime) then
    begin
      Accessed := EncodeDate(STime.wYear, STime.wMonth, STime.wDay);
      Accessed := Accessed + EncodeTime(STime.wHour, STime.wMinute, STime.wSecond,
        STime.wMilliSeconds);
    end;

    // Modified
    FileTimeToLocalFileTime(FTimeM, LTime);
    if FileTimeToSystemTime(LTime, STime) then
    begin
      Modified := EncodeDate(STime.wYear, STime.wMonth, STime.wDay);
      Modified := Modified + EncodeTime(STime.wHour, STime.wMinute, STime.wSecond,
        STime.wMilliSeconds);
    end;

  end;

  Result := Cmd;
end;

Nincsenek megjegyzések:

Megjegyzés küldése