Home > General > How to Get a Unique File Name

How to Get a Unique File Name

December 15th, 1999 m3Rlin Leave a comment Go to comments

You want to save data to a temporary file but you don’t what to file name to use? Well, this function does all the work for you.

function CreateUniqueFileName(sPath: string): string;
var
  chTemp: Char;
begin
  repeat
    Randomize;
    repeat
      chTemp := Chr(Random(43) + 47);
      if Length(Result) = 8 then
        Result := Result + '.'
      else if chTemp in ['0'..'9', 'A'..'Z'] then
        Result := Result + chTemp;
    until Length(Result) = 12;
  until not FileExists(sPath + Result);
end;
  1. hrc
    February 18th, 2009 at 02:45 | #1

    Why not use method GetTempFilename of Microsoft?

    http://msdn.microsoft.com/en-us/library/aa364991(VS.85).aspx

    function DGetTempFileName (const aFolder, aPrefix : string; const aUnique: UINT) : string;
    var
    FileName : array[0..MAX_PATH] of Char;
    begin
    if GetTempFileName(PChar(aFolder), PChar(aPrefix), aUnique, aFileName) = 0 then
    raise Exception.Create (‘GetTempFileName error’);
    Result := FileName;
    end;

    (source Gary Stimson)