Delphi 6: How can I change created filedate (= file creation date)
Asked Answered
M

2

11

I've been searching now for HOURS on Google (and here).

And I cannot find a solution.

I want to CHANGE the "Created Filetime" (= creation filetime) in DELPHI 6.

Not the "Modified file time" (for which a simple call to "FileSetDate()" is needed) and not the "Last accessed file time".

How do I do this?

Picture of what I mean...

Mogerly answered 9/12, 2011 at 13:32 Comment(0)
M
11

Call the SetFileTime Windows API function. Pass nil for lpLastAccessTime and lpLastWriteTime if you only want to modify the creation time.

You will need to obtain a file handle by calling CreateFile, or one of the Delphi wrappers, so this is not the most convenient API to use.

Make life easier for yourself by wrapping the API call up in a helper function that receives the file name and a TDateTime. This function should manage the low-level details of obtaining and closing a file handle, and converting the TDateTime to a FILETIME.

I would do it like this:

const
  FILE_WRITE_ATTRIBUTES = $0100;

procedure SetFileCreationTime(const FileName: string; const DateTime: TDateTime);
var
  Handle: THandle;
  SystemTime: TSystemTime;
  FileTime: TFileTime;
begin
  Handle := CreateFile(PChar(FileName), FILE_WRITE_ATTRIBUTES,
    FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL, 0);
  if Handle=INVALID_HANDLE_VALUE then
    RaiseLastOSError;
  try
    DateTimeToSystemTime(DateTime, SystemTime);
    if not SystemTimeToFileTime(SystemTime, FileTime) then
      RaiseLastOSError;
    if not SetFileTime(Handle, @FileTime, nil, nil) then
      RaiseLastOSError;
  finally
    CloseHandle(Handle);
  end;
end;

I had to add the declaration of FILE_WRITE_ATTRIBUTES because it is not present in the Delphi 6 Windows unit.

Mcpherson answered 9/12, 2011 at 13:44 Comment(2)
Problem time CET and UTC +1Ryley
I can confirm that. (German time) You need to change DateTimeToSystemTime(DateTime, SystemTime) to DateTimeToSystemTime(DateTimeToUTC(DateTime), SystemTime) . A possible implementation for DateTimeToUTC can be found here: delphipraxis.net/207745-utc-local-time.htmlRaye
T
7

Based on FileSetDate, you can write a similar routine:

function FileSetCreatedDate(Handle: Integer; Age: Integer): Integer;
var
  LocalFileTime, FileTime: TFileTime;
begin
  Result := 0;
  if DosDateTimeToFileTime(LongRec(Age).Hi, LongRec(Age).Lo, LocalFileTime) and
    LocalFileTimeToFileTime(LocalFileTime, FileTime) and
    SetFileTime(Handle, @FileTime, nil, nil) then Exit;
  Result := GetLastError;
end;
Theo answered 9/12, 2011 at 13:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.