You want to report the amount of space available on a drive, including total and remaining space.
Sample code folder: Chapter 12\DriveSpace
The My namespace provides access to objects representing the logical drives available on the local workstation. My.Computer. FileSystem.Drives exposes a collection of all logical drives, with each drive stored as a System.IO. DriveInfo object. To retrieve a specific drive by name, use the My.Computer.FileSystem. GetDriveInfo() method, and pass it the name of a logical drive, such as C:\. The returned DriveInfo object includes properties that report the amount of space on the drive.
Create an application that reports the amount of total and free space for any logical drive. Start a new Windows Forms application, and add a ComboBox control named LogicalDrive and three labels for the space totals (FreeSpace, QuotaSpace, and TotalSpace). Set the DropDownStyle property of LogicalDrive to DropDownList, and set the Text properties of the three labels to N/A. You can add some additional field labels if you want, resulting in a form like the one in Figure 12-8.
Figure 12-8. Controls for the drive space sample
Add the following source code to the form's class template:
Private Const NotADrive As String = "<Not Selected>" Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' ----- Fill in the list of logical drives. LogicalDrive.Items.Add(NotADrive) LogicalDrive.SelectedIndex = 0 For Each oneDrive As IO.DriveInfo In _ My.Computer. FileSystem.Drives LogicalDrive.Items.Add(oneDrive.Name) Next oneDrive End Sub Private Sub LogicalDrive_SelectedIndexChanged( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles LogicalDrive.SelectedIndexChanged ' ----- Fill in the drive details. If (LogicalDrive.Text = NotADrive) Then ' ----- <Not Selected> FreeSpace.Text = "N/A" QuotaSpace.Text = "N/A" TotalSpace.Text = "N/A" Else ' ----- A logical drive is selected. Dim oneDrive As IO.DriveInfo = _ My.Computer.FileSystem.GetDriveInfo( _ LogicalDrive.Text) FreeSpace.Text = Format(oneDrive.TotalFreeSpace, _ "#,##0") & " bytes" QuotaSpace.Text = Format(oneDrive.AvailableFreeSpace, _ "#,##0") & " bytes" TotalSpace.Text = Format(oneDrive.TotalSize, _ "#,##0") & " bytes" End If End Sub
To use the program, select a valid logical drive from the LogicalDrive drop-down list, and take careful note of the exact byte counts displayed. Figure 12-9 shows this form in use.
Figure 12-9. Displaying the total and free space on a local hard drive
The DriveInfo object includes three properties that deal with space on a drive:
Recipe 12.1 discusses how to list all the drives on the local system.