How to generate a temporary file name #164

Question
I am trying to find a function that will generate a temporary filename. I know that there is the GetTempFilename function, but I don't have any examples on how to use it.

Answer 1

procedure TForm1.Button1Click(Sender: TObject);
var
  TempFile: array[0..MAX_PATH - 1] of Char;
  TempPath: array[0..MAX_PATH - 1] of Char;
begin
  GetTempPath(MAX_PATH, TempPath);
  if GetTempFileName(TempPath, PChar('abc'), 0, TempFile) = 0 then
    raise Exception.Create(
      'GetTempFileName API failed. ' + SysErrorMessage(GetLastError)
    );
  ShowMessage(TempFile);
end;

Note that this would actually create the temp file in the windows temp folder. Check online help for GetTempFileName, uUnique parameter for details.

Tip by Jack Sudarev

Answer 2

function MyGetTempFile(const APrefix: string): string;
var
  MyBuffer, MyFileName: array[0..MAX_PATH] of char;
begin
  FillChar(MyBuffer, MAX_PATH, 0);
  FillChar(MyFileName, MAX_PATH, 0);
  GetTempPath(SizeOf(MyBuffer), MyBuffer);
  GetTempFileName(MyBuffer, APrefix, 0, MyFileName);
  Result := MyFileName;
end;

Usage:

const
  MyPrefix: String = 'abc';

MyTempFile := MyGetTempFile(MyPrefix);

Tip by Andrei Fomine

Answer 3

Pass in the path and filename you want for the first parameter and your extension as the second. If you want the file to always be myfile1.tmp rather than myfile.tmp leave the last parameter, otherwise set it to false. E.g. to create a file like c:\Tempdir\MyTempFile2000.tmp do

sNewFileName := CreateNewFileName('C:\TempDir\MyTempFile','.tmp');
function CreateNewFileName(BaseFileName: String; Ext: String;
  AlwaysUseNumber: Boolean = True): String;
var
  DocIndex: Integer;
  FileName: String;
  FileNameFound: Boolean;
begin
  DocIndex := 1;
  Filenamefound := False;
  {if number not required and basefilename doesn't exist, use that.}
  if not(AlwaysUseNumber) and (not(fileexists(BaseFilename + ext))) then
  begin
    Filename := BaseFilename + ext;
    FilenameFound := true;
  end;
  while not (FileNameFound) do
  begin
    filename := BaseFilename + inttostr(DocIndex) + Ext;
    if fileexists(filename) then
      inc(DocIndex)
    else
      FileNameFound := true;
  end;
  Result := filename;
end;

I simply check if the file exists and return the first that doesn't.

Tip by Toby Allen

Original resource: The Delphi Pool
Author: Various
Added: 2010/06/02
Last updated: 2010/06/02