Create A Temporary File

The 32-bit API has a call that will create a unique file for you in the Windows temporary directory.


Declare Function OSGetTempPath& Lib "kernel32" Alias "GetTempPathA" 
(ByVal BufferLength&, ByVal Result$)
Declare Function OSGetTempFilename& Lib "kernel32" Alias "GetTempFileNameA" 
(ByVal FilePath$, ByVal Prefix$, ByVal wUnique&, ByVal TempFileName$)
Function sGetTempFile(ByRef sPrefix As String)
Dim sFilePath As String
Dim sTempResult As String
Dim lCharCount As Long
Const MAX_RETURN = 3000
     sTempResult = Space$(MAX_RETURN)
     lCharCount = OSGetTempPath&(MAX_RETURN, sTempResult)
     sFilePath = Left$(sTempResult, lCharCount)
     sTempResult = Space$(MAX_RETURN)
     lCharCount = OSGetTempFilename&(sFilePath, sPrefix, 0, sTempResult)
     sGetTempFile = Left$(sTempResult, lCharCount)
End Function


sTempFile = sGetTempFile(sPrefix:="VBT")

This API call will tag a prefix (up to 3 characters) to the file. This makes it easier for you find, use, or delete your temporary files.

NOTE: Windows will NOT automatically delete these temporary files. So be kind to your user, keep track of them and delete them when the application closes.

This tip is reprinted from the VB Tips & Tricks Volume 1 book.
Parts of this tip was submitted by: David McCarter
Compatible With Visual Basic 4.0 32-bit
Applies To Files