2

How can I "touch" a file, i.e. update its' last modified time to the current time, from within an InnoSetup (Pascal) script?

Ilya
  • 5,533
  • 2
  • 29
  • 57

1 Answers1

5

Here's the code snippet for the TouchFile function:

[Code]
function CreateFile(
    lpFileName             : String;
    dwDesiredAccess        : Cardinal;
    dwShareMode            : Cardinal;
    lpSecurityAttributes   : Cardinal;
    dwCreationDisposition  : Cardinal;
    dwFlagsAndAttributes   : Cardinal;
    hTemplateFile          : Integer
): THandle;
#ifdef UNICODE
 external 'CreateFileW@kernel32.dll stdcall';
#else
 external 'CreateFileA@kernel32.dll stdcall';
#endif

procedure GetSystemTimeAsFileTime(var lpSystemTimeAsFileTime: TFileTime);
 external 'GetSystemTimeAsFileTime@kernel32.dll';

function SetFileModifyTime(hFile:THandle; CreationTimeNil:Cardinal; LastAccessTimeNil:Cardinal; LastWriteTime:TFileTime): BOOL;
external 'SetFileTime@kernel32.dll';

function CloseHandle(hHandle: THandle): BOOL;
external 'CloseHandle@kernel32.dll stdcall';

function TouchFile(FileName: String): Boolean;
const
  { Win32 constants }
  GENERIC_WRITE        = $40000000;
  OPEN_EXISTING        = 3;
  INVALID_HANDLE_VALUE = -1;
var
  FileTime: TFileTime;
  FileHandle: THandle;
begin
  Result := False;
  FileHandle := CreateFile(FileName, GENERIC_WRITE, 0, 0, OPEN_EXISTING, $80, 0);
  if FileHandle <> INVALID_HANDLE_VALUE then
  try
    GetSystemTimeAsFileTime(FileTime);
    Result := SetFileModifyTime(FileHandle, 0, 0, FileTime);
  finally
    CloseHandle(FileHandle);
  end;      
end;
Ilya
  • 5,533
  • 2
  • 29
  • 57
  • Hi there, when I [`was looking`](http://stackoverflow.com/a/10163139/960757) for a `CreateFile` prototype for InnoSetup, I found your code and optimized it a little bit. Also, note this code is for ANSI version of InnoSetup. If you need to use this for Unicode version, you should define the `CreateFile` function import as `CreateFileW` instead of `CreateFileA` or use the trick suggested by [`kobik`](http://stackoverflow.com/users/937125/kobik) in this [`post`](http://stackoverflow.com/a/9670505/960757). +1 for sharing the ides anyway ;-) – TLama Apr 16 '12 at 03:31
  • Right on! Thanks for adding the try-finally. I've modified it for Unicode support now. – Ilya Apr 16 '12 at 21:47