Get a unique name for temporary file

Using GetTempFileName, we can create a unique name for temporary file. It’s useful when your application is using temporary files and you want to save them into default TEMP folder and use a “random” filename.

function GetTempFile(const Extension: string): string;
var Buffer: array[0..MAX_PATH] OF Char;
    aFile : string;
begin
  repeat
    GetTempPath(Sizeof(Buffer)-1, Buffer);
    GetTempFileName(Buffer, '~', 0, Buffer);
    Result := ChangeFileExt(Buffer, Extension);
  until not FileExists(result);
end;

...

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(GetTempFile('.~tp'));
end;