The routines here demonstrate on of the proper methods to
obtain the locations of the operating system paths, ie \Windows, \Winnt, \Windows\System, \Winnt\System32 and Windows' temporary folder via
API.
Also see the new Microsoft-recommended 'Best Practice' using
SHGetFolderPath above. |
Option Explicit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Copyright ©1996-2011 VBnet/Randy Birch, All Rights Reserved.
' Some pages may also contain other copyrights by the author.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Distribution: You can freely use this code in your own
' applications, but you may not reproduce
' or publish this code on any web site,
' online service, or distribute as source
' on any media without express permission.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Private Const MAX_PATH As Long = 260
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 nSize As Long, _
ByVal lpBuffer As String) As Long
Private Sub Command1_Click()
'call the wrapper functions
Label1.Caption = GetWinDir()
Label2.Caption = GetTempDir()
Label3.Caption = GetSystemDir()
End Sub
Private Function GetWinDir() As String
Dim nSize As Long
Dim buff As String
'pad the string for the return value and
'set nSize equal to the size of the string
buff = Space$(MAX_PATH)
nSize = Len(buff)
'call the API
Call GetWindowsDirectory(buff, nSize)
'trim off the trailing null added by the API
GetWinDir = TrimNull(buff)
End Function
Public Function GetTempDir() As String
Dim nSize As Long
Dim buff As String
buff= Space$(MAX_PATH)
nSize = Len(buff)
Call GetTempPath(nSize, buff)
GetTempDir = TrimNull(buff)
End Function
Private Function GetSystemDir() As String
Dim nSize As Long
Dim buff As String
buff = Space$(MAX_PATH)
nSize = Len(buff)
Call GetSystemDirectory(buff, nSize)
GetSystemDir = TrimNull(buff)
End Function
Private Function TrimNull(item As String)
Dim pos As Integer
'double check that there is a chr$(0) in the string
pos = InStr(item, Chr$(0))
If pos Then
TrimNull = Left$(item, pos - 1)
Else
TrimNull = item
End If
End Function |