How can I “touch” a file from within an InnoSetup

2019-07-18 07:57发布

问题:

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

回答1:

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;