Title: How to generate a UNIQUE Temporary Workfile (API Calls)
Question: Generate a unique temporary workfile in the Windows DEFAULT Temp directory. The file is created and closed and is 0 bytes in length. The full path and name of the file is returned. It is the responsibility of the developer to delete this file when finished with. The function takes an optional 3 character string parameter that will prefix the filename, if omitted it defaults to 'XXX'.
Answer:
// ============================================================
// Return a unique filename in Default TEMP Directory
// The file is Created and Closed and is 0 bytes in length.
// Can supply an optional 3 character Prefix (Default is 'XXX')
// ============================================================
function GetUniqueFileName(Prefix : string = 'XXX') : string;
var Retvar : string;
TempPath : string;
begin
SetLength(RetVar,257);
SetLength(TempPath,257);
GetTempPath(257,PChar(TempPath));
GetTempFileName(PChar(TempPath),PChar(Prefix),0,PChar(RetVar));
Result := Retvar;
end;
// Example usage
procedure TForm1.Button1Click(Sender: TObject);
var Fle : file;
FleName : string;
begin
FleName := GetUniqueFileName; // eg. "C:\WINDOWS\TMP\XXXC393.TMP"
Label1.Caption := FleName;
Assignfile(Fle,FleName);
Reset(Fle);
// ... Do something with file
CloseFile(Fle);
DeleteFile(FleName);
end;