Tag Archives: Unique FileName GetTempFileName

Creating a Unique FileName

Text To Create a Unique filename for your working temporary or permanent file you can use a WinAPI function  GetTempFileName .

Here is my variant of making unique filename in specified folder:

function CreateUniqueFileName(sPath, sPrefix, sExtension : string) : string;
  var sFileName : array[0..MAX_PATH] of Char;
begin
  Result := '';
  repeat
    if GetTempFileName(PChar(sPath), PChar(sPrefix), 0, sFileName) <> 0
      then begin
         DeleteFile(sFileName);
         Result := ChangeFileExt(sFileName, sExtension)
      end
      else break; //error or failed
  until not FileExists(Result);
end;

sPath – your folder (you can windows temp folder GetTempPath(SizeOf(Buffer) - 1, Buffer); )
sPrefix – any prefix to attach to filename
sExtension – your extension of filename
if Function fails , empty string is returned.

But I don’t like this approach very much, because Windows creates a temporary file with tmp extension, that you have to delete later, if you don’t want additional files in system. Also deleting files on some OS might be slow.

Much better approach is by creating Unique filenames using GUID – global identifier, it is very little probability that generated GUIDs will be the same.

So here it is my variant of function:

function CreateUniqueGUIDFileName(sPath, sPrefix, sExtension : string) : string;
   var sFileName : string;
        Guid : TGUID;
begin
  Result := '';
  repeat
   SFileName := '';
   CreateGUID(Guid);
   SFileName := sPath + sPrefix + GUIDtoString(GUID);
   Result := ChangeFileExt(sFileName, sExtension)
  until not FileExists(Result);
end;

The variables are the same.

Advertisements