Get a unique name for temporary file
Using GetTempFileName, we can create a unique name for temporary file. It’s useful when your application is using temporary files and you want to save them into default TEMP folder and use a “random” filename.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<span style="font-weight: bold;">function</span> GetTempFile(<span style="font-weight: bold;">const</span> Extension: <span style="font-weight: bold;">string</span>): <span style="font-weight: bold;">string</span>; <span style="font-weight: bold;">var</span> Buffer: <span style="font-weight: bold;">array</span>[0..MAX_PATH] <span style="font-weight: bold;">OF</span> <span style="font-weight: bold;">Char</span>; aFile : <span style="font-weight: bold;">string</span>; <span style="font-weight: bold;">begin</span> <span style="font-weight: bold;">repeat</span> GetTempPath(Sizeof(Buffer)-1, Buffer); GetTempFileName(Buffer, '~', 0, Buffer); Result := ChangeFileExt(Buffer, Extension); <span style="font-weight: bold;">until</span> <span style="font-weight: bold;">not</span> FileExists(result); <span style="font-weight: bold;">end</span>; ... <span style="font-weight: bold;">procedure</span> TForm1.Button1Click(Sender: <span style="font-weight: bold;">TObject</span>); <span style="font-weight: bold;">begin</span> ShowMessage(GetTempFile('.~tp')); <span style="font-weight: bold;">end</span>; |