2007. február 10., szombat

How to generate a temporary file name


Problem/Question/Abstract:

I am trying to find a function that will generate a temporary filename. I know that there is the GetTempFilename function, but I don't have any examples on how to use it.

Answer:

Solve 1:

procedure TForm1.Button1Click(Sender: TObject);
var
  TempFile: array[0..MAX_PATH - 1] of Char;
  TempPath: array[0..MAX_PATH - 1] of Char;
begin
  GetTempPath(MAX_PATH, TempPath);
  if GetTempFileName(TempPath, PChar('abc'), 0, TempFile) = 0 then
    raise Exception.Create('GetTempFileName API failed. ' +
      SysErrorMessage(GetLastError));
  ShowMessage(TempFile);
end;

Note that this would actually create the temp file in the windows temp folder. Check online help for GetTempFileName, uUnique parameter for details.


Solve 2:

function MyGetTempFile(const APrefix: string): string;
var
  MyBuffer, MyFileName: array[0..MAX_PATH] of char;
begin
  FillChar(MyBuffer, MAX_PATH, 0');
    FillChar(MyFileName, MAX_PATH, 0);
    GetTempPath(SizeOf(MyBuffer), MyBuffer);
    GetTempFileName(MyBuffer, APrefix, 0, MyFileName);
    Result := MyFileName;
end;

const
  MyPrefix: string = 'abc';

MyTempFile := MyGetTempFile(MyPrefix);


Solve 3:

Pass in the path and filename you want for the first parameter and your extension as the second. If you want the file to always be myfile1.tmp rather than myfile.tmp leave the last parameter, otherwise set it to false. E.g. to create a file like c:\Tempdir\MyTempFile2000.tmp

sNewFileName := CreateNewFileName('C:\TempDir\MyTempFile', '.tmp');

function CreateNewFileName(BaseFileName: string; Ext: string;
  AlwaysUseNumber: Boolean = True): string;
var
  DocIndex: Integer;
  FileName: string;
  FileNameFound: Boolean;
begin
  DocIndex := 1;
  Filenamefound := False;
  {if number not required and basefilename doesn't exist, use that.}
  if not (AlwaysUseNumber) and (not (fileexists(BaseFilename + ext))) then
  begin
    Filename := BaseFilename + ext;
    FilenameFound := true;
  end;
  while not (FileNameFound) do
  begin
    filename := BaseFilename + inttostr(DocIndex) + Ext;
    if fileexists(filename) then
      inc(DocIndex)
    else
      FileNameFound := true;
  end;
  Result := filename;
end;

I simply checks if the file exists and returns the first that doesn't.

Nincsenek megjegyzések:

Megjegyzés küldése