Working with Drives/Files/Folders using WMI and Visual Basic.NET - How to list all logical disk drives using Visual Basic.NET
(Page 2 of 5 )
Before getting the information on all the logical drives available on your computer, we need to create a wrapper to store the same information. Let us proceed with creating a wrapper:
Public Function getLogicalDriveStructure() As DataTable
Dim dt As New DataTable
dt.Columns.Add(New DataColumn("Description"))
dt.Columns.Add(New DataColumn("DeviceID"))
dt.Columns.Add(New DataColumn("FileSystem"))
dt.Columns.Add(New DataColumn("FreeSpace"))
dt.Columns.Add(New DataColumn("Name"))
dt.Columns.Add(New DataColumn("Size"))
Return dt
End Function
The following method “addLogicalDrive” adds a single row based on the structure you create for the data table using the above method.
Public Sub addLogicalDrive(ByRef dt As DataTable, ByVal Description As String, ByVal DeviceID As String, ByVal FileSystem As String, ByVal FreeSpace As String, ByVal Name As String, ByVal Size As String)
Dim dr As DataRow
dr = dt.NewRow
dr("Description") = Description
dr("DeviceID") = DeviceID
dr("FileSystem") = FileSystem
dr("FreeSpace") = FreeSpace
dr("Name") = Name
dr("Size") = Size
dt.Rows.Add(dr)
End Sub
After creating the wrapper, the following VB.NET code should support some minimum information about the logical drives available in your system.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim searcher As New ManagementObjectSearcher( _
"root\CIMV2", _
"SELECT * FROM Win32_LogicalDisk")
Dim dt As DataTable = globals.getLogicalDriveStructure
For Each queryObj As ManagementObject In searcher.Get()
globals.addLogicalDrive(dt, queryObj("Description"), queryObj("DeviceID"), queryObj("FileSystem"), Convert.ToString(queryObj("FreeSpace")), queryObj("Name"), Convert.ToString(queryObj("Size")))
Next
Me.DataGrid1.DataSource = dt
Catch err As ManagementException
MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
End Try
End Sub
You can achieve the same with VBScript as follows:
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery( _
"SELECT * FROM Win32_LogicalDisk",,48)
For Each objItem in colItems
Wscript.Echo "Description: " & objItem.Description
Wscript.Echo "DeviceID: " & objItem.DeviceID
Wscript.Echo "FileSystem: " & objItem.FileSystem
Wscript.Echo "FreeSpace: " & objItem.FreeSpace
Wscript.Echo "Name: " & objItem.Name
Wscript.Echo "Size: " & objItem.Size
Next
Next: How to list all folders/files information (including sub-folders) using Visual Basic.NET >>
More Windows Scripting Articles
More By Jagadish Chaterjee