Working with Drives/Files/Folders using WMI and Visual Basic.NET - How to list all folders/files information (including sub-folders) using Visual Basic.NET
(Page 3 of 5 )
Before getting the information on folders available on your computer, we need to create a wrapper to store the same information. Let us proceed with creating a wrapper:
Public Function getDirectoryStructure() As DataTable
Dim dt As New DataTable
dt.Columns.Add(New DataColumn("FileName"))
dt.Columns.Add(New DataColumn("Path"))
dt.Columns.Add(New DataColumn("Readable"))
dt.Columns.Add(New DataColumn("Writeable"))
Return dt
End Function
The following method “addDirectory” adds a single row based on the structure you create for the data table using the above method.
Public Sub addDirectory(ByRef dt As DataTable, ByVal FileName As String, ByVal Path As String, ByVal Readable As String, ByVal Writeable As String)
Dim dr As DataRow
dr = dt.NewRow
dr("FileName") = FileName
dr("Path") = Path
dr("Readable") = Readable
dr("Writeable") = Writeable
dt.Rows.Add(dr)
End Sub
After creating the wrapper, the following VB.NET code should support some minimum information about the “folders” 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_Directory")
Dim dt As DataTable = globals.getDirectoryStructure
For Each queryObj As ManagementObject In searcher.Get()
globals.addDirectory(dt, queryObj("FileName"), queryObj("Path"), queryObj("Readable"), queryObj("Writeable"))
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_Directory",,48)
For Each objItem in colItems
Wscript.Echo "FileName: " & objItem.FileName
Wscript.Echo "Path: " & objItem.Path
Wscript.Echo "Readable: " & objItem.Readable
Wscript.Echo "Writeable: " & objItem.Writeable
Next
You can get the list of files by replacing “Win32_directory” with “CIM_DataFile.”
Next: How to retrieve the sub-folder information of a particular folder using Visual Basic.NET >>
More Windows Scripting Articles
More By Jagadish Chaterjee