The following main form unit example has a TButton and a TOpenDialog dropped on it.
unit mainSetFileTime;
{$mode objfpc}{$H+}
interface
uses
windows, Classes, SysUtils, FileUtil, Forms, Dialogs, StdCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
BSetFileTime: TButton;
OpenDialog1: TOpenDialog;
procedure BSetFileTimeClick(Sender: TObject);
private
function SetFileDate(const aFilename: string; aDate: TDateTime): boolean;
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.BSetFileTimeClick(Sender: TObject);
begin
if OpenDialog1.Execute then
if SetFileDate(OpenDialog1.FileName, Now) then
ShowMessageFmt('All OS file dates of %s are set to this moment''s date and time',
[OpenDialog1.FileName])
else ShowMessage('SetFileDate() function failed');
end;
function TForm1.SetFileDate(const aFilename: string; aDate: TDateTime): boolean;
var
fileHandle: THandle;
fileTime: TFILETIME;
LFileTime: TFILETIME;
LSysTime: TSystemTime;
begin
Result:=False;
try
DecodeDate(aDate, LSysTime.Year, LSysTime.Month, LSysTime.Day);
DecodeTime(aDate, LSysTime.Hour, LSysTime.Minute, LSysTime.Second, LSysTime.Millisecond);
if SystemTimeToFileTime(LSysTime, LFileTime) then
begin
if LocalFileTimeToFileTime(LFileTime, fileTime) then
begin
fileHandle:=FileOpenUTF8(aFilename, fmOpenReadWrite or fmShareExclusive);
if SetFileTime(fileHandle, fileTime, fileTime, fileTime) then
Result:=True;
end;
end;
finally
FileClose(fileHandle);
end;
end;
end.