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.
Advertisement
June 27th, 2011 at 4:52 pm
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.
January 2nd, 2012 at 8:46 am
Oh, didn’t know that.
Thanks for the info. I guess I just need a good book on new methods in recent Delphi.