Author: Jonas Bilinkevicius
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:
1 procedure TForm1.Button1Click(Sender: TObject);
2 var
3 TempFile: array[0..MAX_PATH - 1] of Char;
4 TempPath: array[0..MAX_PATH - 1] of Char;
5 begin
6 GetTempPath(MAX_PATH, TempPath);
7 if GetTempFileName(TempPath, PChar('abc'), 0, TempFile) = 0 then
8 raise Exception.Create('GetTempFileName API failed. ' +
9 SysErrorMessage(GetLastError));
10 ShowMessage(TempFile);
11 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:
12 function MyGetTempFile(const APrefix: string): string;
13 var
14 MyBuffer, MyFileName: array[0..MAX_PATH] of char;
15 begin
16 FillChar(MyBuffer, MAX_PATH, 0');
17 FillChar(MyFileName, MAX_PATH, 0);
18 GetTempPath(SizeOf(MyBuffer), MyBuffer);
19 GetTempFileName(MyBuffer, APrefix, 0, MyFileName);
20 Result := MyFileName;
21 end;
22
23 const
24 MyPrefix: string = '
25
26 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
27
28 sNewFileName := CreateNewFileName('C:\TempDir\MyTempFile', '.tmp');
29
30 function CreateNewFileName(BaseFileName: string; Ext: string;
31 AlwaysUseNumber: Boolean = True): string;
32 var
33 DocIndex: Integer;
34 FileName: string;
35 FileNameFound: Boolean;
36 begin
37 DocIndex := 1;
38 Filenamefound := False;
39 {if number not required and basefilename doesn't exist, use that.}
40 if not (AlwaysUseNumber) and (not (fileexists(BaseFilename + ext))) then
41 begin
42 Filename := BaseFilename + ext;
43 FilenameFound := true;
44 end;
45 while not (FileNameFound) do
46 begin
47 filename := BaseFilename + inttostr(DocIndex) + Ext;
48 if fileexists(filename) then
49 inc(DocIndex)
50 else
51 FileNameFound := true;
52 end;
53 Result := filename;
54 end;
I simply checks if the file exists and returns the first that doesn't.
|