Skip Navigation Links.
Getting a Temp File Name from Windows
Language(s):Visual Basic 6.0
Category(s):Utilities

Getting a Temp File Name from Windows using GetTempPath, GetTempFileName.

' 1) Create a new project. Form1 will be created by default.
' 2) Add a Command Button to the Form. 
' 3) From the menu select Project|Add Module. Module1 will be created by default
' 4) Paste the following code into the declarations section of Form1:

' --- Begin code for Form1

'Getting a Temp File Name from Windows
'
'Jon Vote, Idioma Software Inc.
'
'02/2002
'
'www.idioma-software.com

Option Explicit

Private Sub Command1_Click()
  
  Dim strTempPath As String
  Dim strPrefix As String
  
  On Error GoTo err_Command1_Click
  
  strTempPath = InputBox$("Pathname for temp file (Optional):", "Temp Path Name", TempPath())
  strPrefix = InputBox$("Prefix for temp file (Optional):", "Prefix", "~")
  
  MsgBox "Temp Filename: " & TempFileName(strTempPath, strPrefix)
  
  Exit Sub
  
err_Command1_Click:
  
  MsgBox Err.Description
  
End Sub

' --- End code for Form1 ---

' 5) Paste the followin code into Module1:

' --- Begin code for Module1 ---

'Getting a Temp File Name from Windows
'
'Jon Vote, Idioma Software Inc.
'
'02/2002
'
'www.idioma-software.com

Option Explicit

Declare Function GetTempPath Lib "Kernel32" Alias "GetTempPathA" (ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long
Declare Function GetTempFileName Lib "Kernel32" Alias "GetTempFileNameA" (ByVal lpszPath As String, ByVal lpPrefixString As String, ByVal wUnique As Long, ByVal lpTempFileName As String) As Long

Public Function TempFileName(Optional varTempPath As Variant, Optional varPrefix As Variant) As String
  
 Dim strPrefix As String
 Dim strTempFileName As String
 Dim strTempPath As String
 Dim lngRC As Long
  
 If IsMissing(varTempPath) Then
   strTempPath = TempPath()
 ElseIf Trim$(varTempPath) = "" Then
   strTempPath = TempPath()
 Else
   strTempPath = varTempPath
 End If
 
 If IsMissing(varPrefix) Then
   strPrefix = "~"
 ElseIf Trim$(varPrefix) = "" Then
   strPrefix = "~"
 Else
   strPrefix = varPrefix
 End If
 
 strTempFileName = Space$(255)
 lngRC = GetTempFileName(strTempPath, strPrefix, 0, strTempFileName)
 TempFileName = strTempFileName

End Function

Public Function TempPath()
    
  Dim lngRC As Long
  Dim strTempPath As String
  
  strTempPath = Space$(256)
  lngRC = GetTempPath(256, strTempPath)
  TempPath = strTempPath
  
End Function

' --- End code for Module1 ---
This article has been viewed 3429 times.
The examples on this page are presented "as is". They may be used in code as long as credit is given to the original author. Contents of this page may not be reproduced or published in any other manner what so ever without written permission from Idioma Software Inc.