Most of today’s computers have a CD drive, but you cannot
really be sure. In addition, many systems have two drives—for example, a CD
burner and a DVD-CD reader. If you are writing a Visual Basic program that
makes use of the CD drive, it is usually a good idea to check to see what is
actually available.

This tip shows you how to get a list of the CD-ROM drives on
a system. It relies on two API functions whose declarations are shown here
(along with a needed constant):

Public Declare Function GetDriveType Lib "kernel32" _
        Alias "GetDriveTypeA" (ByValnDrive As String) As Long
Public Declare Function GetLogicalDriveStrings Lib "kernel32" _
        Alias "GetLogicalDriveStringsA" (ByValnBufferLength As Long, _
        ByVallpBuffer As String) As Long
Public Const DRIVE_CDROM = 5

Then, the following function will return a string that lists
all the CD-ROM drives (with each drive letter preceded by the identifying text

Private Function GetCDROMs() As String

    Dim Drives As String
    Dim Drive As String
    Dim buf As String

    Drives = Space(255)
    Drives = Left$(Drives, GetLogicalDriveStrings(255, ByVal Drives))
    While InStr(Drives, "\")
        Drive = Left$(Drives, InStr(Drives, "\"))
        If GetDriveType(Drive) = DRIVE_CDROM Then
            buf = buf & "[CD-ROM] " & Drive & vbCrLf
        End If
        Drives = Mid$(Drives, Len(Drive) + 2)

    ListCDROMs = buf
End Function

For example, when run on my system, this returns the

[CD-ROM] E:\
[CD-ROM] F:\

This technique does not tell you what kind of CD drive(s) are
available—CD reader, CD burner, DVD, etc.—but since all of these types can read
CD-ROMs, it still provides useful information.

Advance your scripting skills to the next level with TechRepublic’s free Visual Basic newsletter, delivered each Friday. Automatically sign up today!