Help & Manual authoring tool
Sometimes we need to create temporary files with unique names; here's how

Creating a unique temporary file

Copyright © 2000 Ernesto De Spirito

InstallAWARE - MSI without rocket science

CreateTempFile

This function (see source code below) creates a unique file in the temporary directory and returns its path name. The name of the file has the form "~XXXX.TMP", where XXXX is the hexadecimal representation of a two-byte integer (determined using the system clock).

uses SysUtils, Windows;

function CreateTempFile: TFileName;
// Creates a temporal file and returns its path name
var
  TempFileName: array [0..MAX_PATH-1] of char;
begin
  if GetTempFileName(PChar(GetTempDir), '~', 0, TempFileName) = 0 then
    raise Exception.Create(SysErrorMessage(GetLastError));
  Result := TempFileName;
end;

Sample call

This temporary file is not deleted automatically by Windows, so your application is responsible for deleting the files created with this function when it no longer needs them. For example you can use a code like this:

procedure TForm1.Button1Click(Sender: TObject);
var
  TempFileName: TFileName;
begin
  TempFileName := CreateTempFile;
  try
    // Open the file
    // Use the file
    // Close the file
  except
    try
      // Close the file if opened
    finally
      SysUtils.DeleteFile(TempFileName);
    end;
  end;
end;
JfControls Library - for Delphi and C++ Builder
Copyright © 2000/2006 Ernesto De Spirito.   All rights reserved.