All Snippets
Top 100 Snippets

By Language

GBIC >> Source Code >> Visual Basic >> Snippet

Get list of drive letters

'4 approaches are provided in this snippet - API, FSO, Drive Control, Pure VB (no controls/objects)

'use API
Private Declare Function GetDriveType Lib "kernel32" Alias "GetDriveTypeA" ( ByVal nDrive As String ) As Long
Private Declare Function GetLogicalDriveStrings Lib "kernel32" Alias "GetLogicalDriveStringsA" ( ByVal nBufferLength As Long , ByVal lpBuffer As String ) As Long
Private Const DRIVE_REMOVABLE = 2
Private Const DRIVE_FIXED = 3
Private Const DRIVE_REMOTE = 4
Private Const DRIVE_CDROM = 5
Private Const DRIVE_RAMDISK = 6

Dim i As Long , DList As String , DArray() As String
i = GetLogicalDriveStrings(0, DList)
DList = Space$(i)
i = GetLogicalDriveStrings(i, DList)
DArray = Split(DList, Chr $(0))


'using the FileSystemObject (create a project reference to 'Microsoft Scripting Runtime'
Dim f As New FileSystemObject, x As Drive, i As Long
Redim Letters(f.Drives.Count - 1)
For Each x In f.Drives
   Letters(i) = x.DriveLetter
Next x

'pure VB approach, using the Drive control
'drive letters are found in positions 0-UBound(Letters)
Dim i As Long , Letters()
Redim Letters(Drive1.ListCount - 1)
For i = 0 To Drive1.ListCount - 1
   Letters(i) = Left$(Drive1.List(i), 1)
Next i

'pure VB approach, no controls required
'drive letters are found in positions 1-UBound(Letters)
Dim i As Long , Letters()
Redim Letters(0)
For i = 1 To 26
    If ValidDrive( Chr (96 + i)) = True Then
        Redim Preserve Letters( Ubound (Letters) + 1)
      Letters( Ubound (Letters)) = Chr (96 + i)
    End If
Next i

Function ValidDrive(D As String ) As Boolean
  On Error Goto driveerror
  Dim temp As String
 temp = CurDir
 ChDrive D
 ChDir temp
 ValidDrive = True
  Exit Function
End Function