Visual Basic Code of the Week (COTW)
http://www.codeoftheweek.com
Issue #78
Online Version at http://www.codeoftheweek.com/membersonly/bi/0078.html (paid subscribers only)
All content and source code is Copyright (c) 1999 by C&D Programming Corp. No part of this issue can be reprinted or distributed in any manner without express written permission of C&D Programming Corp.

Deal of the Week

Get your copy of NetMon, the Internet Performance Monitor for only $10. Download a free evaluation copy of NetMon at http://www.codeoftheweek.com/netmon/index.html

Bonus Issue Update

We have updated issue number 23 (Parsing words/tokens using any delimiter) to support multi-character delimiters. If you are a paid subscriber, download the updated source code at http://www.codeoftheweek.com/membersonly/bi/0023.html

In this Issue

In this issue we discuss how to get the current temporary path or a unique temporary filename using several API calls.

This source code is designed for VB 5.0 and up. It can be used with VB 4.0 32-bit by changing the Optional declarations. Questions? Email us at questions@codeoftheweek.com.

basFileSystem

The basFileSystem module includes two functions: TempPath and TempFile. TempPath retrieves the Windows temporary directory and TempFile retrieves a unique temporary filename.

TempPath

Public Function TempPath() As String

TempPath retrieves the directory where most temporary files are stored while using Windows 95/98/NT. Under Windows 95/98 this function will retrieve the temporary path as follows:

Under Windows NT it will retrieve the temporary path as follows (NOTE: The TempPath function does not verify that the directory specified by the TMP or TEMP environment variables exists):

TempFile

Public Function TempFile(Optional sPrefix As String = "VB_", Optional sTempFileLocation As String = "") As String

TempFile attempts to form a filename using the Prefix you supplied and a unique number based on the current system time. If a file with the resulting file name exists, the number is increased by one and the test for existence is repeated. Testing continues until a unique file name is found. TempFile then creates a file by that name and closes it.

The format of the filename created will be pppnnnn.tmp and it will be created by default in the standard Windows temporary directory as returned from TempPath. ppp is the value specified in sPrefix and nnnn is a unique number based on the current system time.

Sample Usage

The below sample describes how to use the TempPath and TempFile functions.

    MsgBox "Windows Temporary Directory: " & TempPath & vbCr & _
            "Sample Temporary Filename: " & TempFile & vbCr & _
            "Temp File with a custom prefix: " & TempFile("CTW")

Source Code

Just create a new Module and then paste this source code into it. You should name the class basFileSystem.

'----------------------------------------------------------------------
'
'   Module Name:    basFileSystem
'   Written By:     C&D Programming Corp.
'   Create Date:    2/99
'   Copyright:      Copyright 1999 by C&D Programming Corp.  Source
'                   code may not be reproduced except for use in a
'                   compiled executable.  All rights reserved.  If
'                   you would like to reprint any or all of this
'                   code please email us at info@codeoftheweek.com
'----------------------------------------------------------------------
Option Explicit

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

Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" _
        (ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long

Private Const MAX_PATH = 260


' Windows 95/98: The GetTempPath function gets the temporary file path as follows:
'
'   The path specified by the TMP environment variable.
'   The path specified by the TEMP environment variable, if TMP is not defined or if
'       TMP specifies a directory that does not exist.
'   The current directory, if both TMP and TEMP are not defined or specify nonexistent
'       directories.

' Windows NT: The GetTempPath function does not verify that the directory specified
'       by the TMP or TEMP environment variables exists. The function gets the
'       temporary file path as follows:
'
'   The path specified by the TMP environment variable.
'   The path specified by the TEMP environment variable, if TMP is not defined.
'   The Windows directory, if both TMP and TEMP are not defined

Public Function TempPath() As String
    Dim sTemp As String
    Dim lRet As Long
    Dim lLen As Long

    On Error GoTo Handler
    sTemp = Space$(MAX_PATH)
    lLen = GetTempPath(MAX_PATH, sTemp)
    TempPath = Left(sTemp, lLen)
    Exit Function

Handler:
    Err.Raise Err.Number, "TempPath", Err.Description
End Function


'   Attempts to form a unique filename based on the sPrefix and the current system time.
'   If a file with the resulting file name exists, the number is increased by one and
'   the test for existence is repeated. Testing continues until a unique file name
'   is found. TempFileName then creates a file by that name and closes it.

Public Function TempFile(Optional sPrefix As String = "VB_", Optional sTempFileLocation As String = "") As String
    Dim sTempFile As String
    Dim lLen As Long
    Dim iNull As Integer

    On Error GoTo Handler
    If sTempFileLocation = "" Then
        sTempFileLocation = TempPath
    End If
    sTempFile = Space$(MAX_PATH)
    lLen = GetTempFileName(sTempFileLocation, sPrefix, 0, sTempFile)

    ' find null and trim everything after it.
    iNull = InStr(sTempFile, vbNullChar)
    If iNull = 0 Then
        TempFile = ""
    Else
        TempFile = Left(sTempFile, iNull - 1)
    End If
    Exit Function

Handler:
    Err.Raise Err.Number, "TempFile", Err.Description
End Function

This document is available on the web

Paid subscribers can view this issue in HTML format. There is no additional source or information in the HTML formatted document. It just looks a little better since we have included some HTML formatting. Just point your browser to link at the top of this document.

Other links

Contact Information

C&D Programming Corp.
PO Box 20128
Floral Park, NY 11002-0128
Phone or Fax: (212) 504-7945
Email: info@codeoftheweek.com
Web: http://www.codeoftheweek.com