Home  |   French  |   About  |   Search  | mvps.org  

What's New
Table Of Contents
Credits
Netiquette
10 Commandments 
Bugs
Tables
Queries
Forms
Reports
Modules
APIs
Strings
Date/Time
General
Downloads
Resources
Search
Feedback
mvps.org

In Memoriam

Terms of Use


VB Petition

API: Return a temporary unique file name

Author(s)
Terry Kreft

(Q)    How do I return a temporary Unique file name?

(A)    Paste the following code in a new module and use this convention to return a temp file name.


'Call TempFile(False) to get a unique temporary filename or
'Call TempFile(True) to create a temporary file (0 bytes)

'**************** Code Start **********************
'This code was originally written by Terry Kreft. 
'It is not to be altered or distributed, 
'except as part of an application. 
'You are free to use it in any application,  
'provided the copyright notice is left unchanged.
'
'Code Courtesy of
'Terry Kreft

Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" _
    (ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long
Private 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
Function TempDir() As String
Dim lngRet As Long
Dim strTempDir As String
Dim lngBuf As Long
    strTempDir = String$(255, 0)
    lngBuf = Len(strTempDir)
    lngRet = GetTempPath(lngBuf, strTempDir)
    If lngRet > lngBuf Then
        strTempDir = String$(lngRet, 0)
        lngBuf = Len(strTempDir)
        lngRet = GetTempPath(lngBuf, strTempDir)
    End If
    TempDir = Left(strTempDir, lngRet)
End Function
'Creates and/or returns the name of a unique temp file
'Create determines whether to just return a filename or to crete the file.
'lpPrefixString defines the first three letters of the temp filename
'if left blank will use "tmp"
'lpszPath defines the directory path to the temporary file, if left blank will
'use the system temp directory setting
Function TempFile(Create As Boolean, Optional lpPrefixString As Variant, _
        Optional lpszPath As Variant) As String
Dim lpTempFileName As String * 255
Dim strTemp As String
Dim lngRet As Long
    If IsMissing(lpszPath) Then
        lpszPath = TempDir
    End If
    If IsMissing(lpPrefixString) Then
        lpPrefixString = "tmp"
    End If
    lngRet = GetTempFileName(lpszPath, lpPrefixString, 0, lpTempFileName)
    strTemp = lpTempFileName
    lngRet = InStr(lpTempFileName, Chr$(0))
    strTemp = Left(lpTempFileName, lngRet - 1)
    If Create = False Then
        Kill strTemp
        Do Until Dir(strTemp) = "": DoEvents: Loop
    End If
    TempFile = strTemp
End Function

'**************** Code End **********************

© 1998-2010, Dev Ashish & Arvin Meyer, All rights reserved. Optimized for Microsoft Internet Explorer