Working with Drives/Files/Folders using WMI and Visual Basic.NET

This article explains how to retrieve folder/file/drive information dynamically using Visual Basic.NET and VBScript.

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 20
December 28, 2005
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

A downloadable file for this article is available here.

The sample downloadable solution (zip) is entirely developed using Visual Studio.NET 2003 Enterprise Architect on Windows Server 2003 Standard Edition.  But, I am confident that it would work with other versions of Windows (which support .NET 1.1) as well.

I contributed several articles previously about WMI with VB.NET and VBScript (including some on introductory or basic topics of WMI).  I even contributed a series (of about six articles) about “WMI Programming on VB.NET” covering several aspects of WMI.  I strongly suggest you go through that series, before going through this article.

How to list all disk drives using Visual Basic.NET

Before getting out the information on drives available in on your computer, we need to create a wrapper to store the same information.  Let us proceed with creating a wrapper:

 Public Function getDiskDriveStructure() As DataTable
        Dim dt As New DataTable
        dt.Columns.Add(New DataColumn("Caption"))
        dt.Columns.Add(New DataColumn("DeviceID"))
        dt.Columns.Add(New DataColumn("Partitions"))
        dt.Columns.Add(New DataColumn("Size"))
        Return dt
    End Function

The following method “addDiskDrive” adds a single row based on the structure you create for the data table using the above method.

    Public Sub addDiskDrive(ByRef dt As DataTable, ByVal Caption As String, ByVal DeviceID As String, ByVal Partitions As String, ByVal Size As String)
        Dim dr As DataRow
        dr = dt.NewRow
        dr("Caption") = Caption
        dr("DeviceID") = DeviceID
        dr("Partitions") = Partitions
        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 “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_DiskDrive")
            Dim dt As DataTable = globals.getDirectoryStructure
            For Each queryObj As ManagementObject In searcher.Get()
                globals.addDirectory(dt, queryObj("Caption"), queryObj("DeviceID"), Convert.ToString(queryObj("Partitions")), 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_DiskDrive",,48)
For Each objItem in colItems
    Wscript.Echo "Caption: " & objItem.Caption
    Wscript.Echo "DeviceID: " & objItem.DeviceID
    Wscript.Echo "Partitions: " & objItem.Partitions
    Wscript.Echo "Size: " & objItem.Size
Next

If you include “DriveType=3” in the query, it will return results only for hard disks.

How to list all logical disk drives using Visual Basic.NET

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

How to list all folders/files information (including sub-folders) using Visual Basic.NET

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.”

How to retrieve the sub-folder information of a particular folder using Visual Basic.NET

I am trying to use the same wrapper I created in the previous section.  So, let us directly proceed with the code.

Try
            Dim searcher As New ManagementObjectSearcher( _
                   "root\CIMV2", _
                   "Associators of {Win32_Directory.Name='d:\DataAccessLibrary'} " _
                           & "Where AssocClass =
Win32_Subdirectory " _
                            & "ResultRole = PartComponent")
 
            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

You can achieve the same with VBScript as follows:

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery( _
    "Associators of {Win32_Directory.Name='d:\DataAccessLibrary'} " _
                           & "Where AssocClass = Win32_Subdirectory " _
                            & "ResultRole = PartComponent",,48)
For Each objItem in colItems
    Wscript.Echo "Description: " & objItem.Description
    Wscript.Echo "ProxyPortNumber: " & objItem.ProxyPortNumber
    Wscript.Echo "ProxyServer: " & objItem.ProxyServer
    Wscript.Echo "ServerName: " & objItem.ServerName
Next

How to rename a folder using Visual Basic.NET

As I am operating against a particular WMI object, we do not need a wrapper for this.  We are not retrieving any information at this point.

The following code renames the folder you specify.

Try
            Dim classInstance As New ManagementObject( _
                "root\CIMV2", _
                "Win32_Directory.Name='d:\DataAccessLibrary'", _
                Nothing)
            Dim inParams As ManagementBaseObject = _
                classInstance.GetMethodParameters("Rename")
            inParams("FileName") = "d:\DataAccessLibrary2"
            Dim outParams As ManagementBaseObject = _
                classInstance.InvokeMethod("Rename", inParams, Nothing)
            MessageBox.Show(outParams("ReturnValue"))
        Catch err As ManagementException
            MessageBox.Show("An error occurred while trying to execute the WMI method: " & err.Message)
        End Try

You can achieve the same with VBScript as follows:

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set objShare = objWMIService.Get("Win32_Directory.Name='d:\DataAccessLibrary'")
 
Set objInParam = objShare.Methods_("Rename"). _
    inParameters.SpawnInstance_()
 
 
objInParam.Properties_.Item("FileName") =  "d:\DataAccessLibrary2"
 
Set objOutParams = objWMIService.ExecMethod("Win32_Directory.Name=' d:\DataAccessLibrary '", "Rename", objInParam)
 
Wscript.Echo "Out Parameters: "
Wscript.echo "ReturnValue: " & objOutParams.ReturnValue

How to delete a folder using Visual Basic.NET

As I am operating against a particular WMI object, we do not need a wrapper for this.  We are not retrieving any information at this point.

The following code renames the folder you specify.

Try
            Dim classInstance As New ManagementObject( _
                "root\CIMV2", _
                "Win32_Directory.Name='d:\DataAccessLibrary'", _
                Nothing)
            Dim inParams As ManagementBaseObject = _
                classInstance.GetMethodParameters("Delete")
            Dim outParams As ManagementBaseObject = _
                classInstance.InvokeMethod("Delete", inParams, Nothing)
            MessageBox.Show(outParams("ReturnValue"))
        Catch err As ManagementException
            MessageBox.Show("An error occurred while trying to execute the WMI method: " & err.Message)
        End Try

You can achieve the same with VBScript as follows:

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set objShare = objWMIService.Get("Win32_Directory.Name='d:\DataAccessLibrary'")
 
Set objInParam = objShare.Methods_("Delete"). _
    inParameters.SpawnInstance_()
 
Set objOutParams = objWMIService.ExecMethod("Win32_Directory.Name=' d:\DataAccessLibrary '", "Delete", objInParam)
 
Wscript.Echo "Out Parameters: "
Wscript.echo "ReturnValue: " & objOutParams.ReturnValue

All the above topics are only simple programs to get you started immediately.  You can still find much more information on every file/folder/drive using several other properties.  You can also use several operations other than just deleting and renaming.  I suggest you check MSDN for further information about properties, methods, and so on related to WMI.

Any comments, suggestions, bugs, errors, feedback etc. are highly appreciated at jag_chat@yahoo.com.

blog comments powered by Disqus
WINDOWS SCRIPTING ARTICLES

- More Windows Scripting Workarounds from Nilpo
- Overloading Methods and More in VBScript
- Improving MFC for Windows Vista
- Regular Expressions in VBScript
- Working with Dates in WMI
- Completing Calendars with VBScript Date Func...
- Building Calendars with VBScript Date Functi...
- Working With Dates and Times in VBScript
- Designing WCF DataContract Classes Using the...
- Understanding Dates and Times in VBScript
- Working With Arrays in VBScript
- Compressed Folders in WSH
- Using .NET Interops in VBScript
- Nilpo`s Scripting Secrets, Vol I
- Database operations using Silverlight 2.0 WC...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 3 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials