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

2 responses to “Creating a Unique FileName

  • Linas

    Why are you reinventing the wheel?

    uses
    IOUtils;

    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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

w

Connecting to %s

%d bloggers like this: