How to retrieve various system paths

Applies To

OS:
VB:
NT, 9x, 2000
5, 6

For your programming enjoyment below, we provide the code to retrieve the Windows directory, Windows System directory and Temporary directory. 

Add the following to a .BAS, .FRM or .CLS


Private Declare Function GetSystemDirectory Lib "kernel32" Alias _
    "GetSystemDirectoryA" (ByVal lpBuffer As String, _
    ByVal nSize As Long) As Long

Private Declare Function GetWindowsDirectory Lib "kernel32" Alias _
    "GetWindowsDirectoryA" (ByVal lpBuffer As String, _
    ByVal nSize As Long) As Long


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

'Get the Windows directory
Public Function WindowsDirectory() As String
    Dim Buffer As String * 255
    Dim Length As Long
    
    'get the path
    Length = GetWindowsDirectory(Buffer, Len(Buffer))
    
    'Length contains the number of chars returned up to the NULL
    WindowsDirectory = Left$(Buffer, Length)
End Function


'Get the Windows System directory
Public Function SystemDirectory() As String
    Dim Buffer As String * 255
    Dim Length As Long
    
    'get the path
    Length = GetSystemDirectory(Buffer, Len(Buffer))
    
    'Length contains the number of chars returned up to the NULL
    SystemDirectory = Left$(Buffer, Length)
End Function

'Get the Temp directory
Public Function TempDirectory() As String
    Dim Buffer As String * 512
    Dim Length As Long
    
    'get the path
    Length = GetTempPath(Len(Buffer), Buffer)
    
    'Length contains the number of chars returned up to the NULL
    'As a bonus, the Temp path is terminated with a slash
    TempDirectory = Left$(Buffer, Length)
   
End Function