You need access to the list of drives available on the local workstation.
Sample code folder: Chapter 12\EnumerateDrives
Use the My.Computer.FileSystem.Drives collection to enumerate through the logical drives.
If you have a form (Form1) with a ListBox control (ListBox1), the following code adds the name of each available drive to the list when the form first opens:
Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load For Each oneDrive As IO. DriveInfo In _ My.Computer. FileSystem.Drives ListBox1.Items.Add(oneDrive) Next oneDrive End Sub
That code adds complete objects of type System.IO.DriveInfo to the list. If you only want to add the drive names, use this code instead:
Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load For Each oneDrive As IO.DriveInfo In _ My.Computer.FileSystem.Drives ListBox1.Items.Add(oneDrive.Name) Next oneDrive End Sub
Each added item appears as X:\, where X is replaced by the drive letter. Figure 12-1 shows the output of this code on a computer with just a "C" drive.
Figure 12-1. The list of drives on a typical one-drive workstation
The My.Computer.FileSystem.Drives collection provides access to details about each local or network drive attached to the workstation. Since it is a collection that exposes the IEnumerable interface, you can use it in a For Each statement, accessing each drive object in the collection.
The System.IO.DriveInfo object includes the following useful properties:
Recipe 12.8 shows how to iterate directories within a drive.