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;
  Result := '';
    if GetTempFileName(PChar(sPath), PChar(sPrefix), 0, sFileName) <> 0
      then begin
         Result := ChangeFileExt(sFileName, sExtension)
      else break; //error or failed
  until not FileExists(Result);

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;
  Result := '';
   SFileName := '';
   SFileName := sPath + sPrefix + GUIDtoString(GUID);
   Result := ChangeFileExt(sFileName, sExtension)
  until not FileExists(Result);

The variables are the same.


2 responses to “Creating a Unique FileName

  • Linas

    Why are you reinventing the wheel?


    And now you can use TPath.GetGUIDFileName or TPath.GetTempFileName. These functions will surely be cross platform and 64 bit capable in the future.

    P.S. It is always a good practice to pass const string parameters to functions if you don’t need to modify them. Delphi won’t make a string copy in the routine that way.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: