Getting CD drive letter in VB.NET

5.9k Views Asked by At

I am using the following code to get a list of the letters for each drive on my computer. I want to get the drive letter of the CD drive from this list. How do I check it?

The code I am using to get list is as below:

In the Form.Load event:

    cmbDrives.DropDownStyle = ComboBoxStyle.DropDownList
    Dim sDrive As String, sDrives() As String

    sDrives = ListAllDrives()

    For Each sDrive In sDrives

    Next
    cmbDrives.Items.AddRange(ListAllDrives())

. . .

Public Function ListAllDrives() As String()
    Dim arDrives() As String
    arDrives = IO.Directory.GetLogicalDrives()
    Return arDrives
End Function
2

There are 2 best solutions below

1
On BEST ANSWER

Tested, and returns the correct results on my computer:

Dim cdDrives = From d In IO.DriveInfo.GetDrives() _
                Where d.DriveType = IO.DriveType.CDRom _
                Select d

For Each drive In cdDrives
    Console.WriteLine(drive.Name)
Next

Assumes 3.5, of course, since it's using LINQ. To populate the list box, change the Console.WriteLine to ListBox.Items.Add.

0
On
For Each drive In DriveInfo.GetDrives()

   If drive.DriveType = DriveType.CDRom Then
       MessageBox.Show(drive.ToString())
   Else 
       MessageBox.Show("Not the cd or dvd rom" & " " & drive.ToString())
   End If

Next