How can I gather Disk statistics

partham

Active member
Joined
Dec 27, 2005
Messages
41
Location
Kolkata, India
Programming Experience
10+
Dear Sir,

We would like to have some basic details about the disk on which our application is running like Disk Space available, etc. This is to request you to kindly let us know the class which can provide us this information.

Thanks in advance.

Regards,
 
You should give WMI Code Creator 1.0 a spin, just select in query tab the Win32_LogicalDisk class and the properties you want, and it will generate the code.
 
Performance counters are another great way to do this. With a few simple lines of code you can gather anything from free space down to about of time spent reading/writing during the sample period.
 
Dear Mr. John,

You have exposed me to something awesome. However, even after reasonable effort, I am unable to use the code as I do not know what libraries to include. This is to request you to kindly guide me to one sample code where it has been implemented using VB.Net.

Regards,
 
The codes generated are complete, when targeting local machine they are Concole Applications (as you see they use the Console class). When you have selected a class and a property and click 'Execute' it is the full .Net application given by the code that is compiled and executed.

Whether console or windows forms application doesn't really matter, what is important is the WMI code you get 'for nothing' that can be transported into your own application.

On top of the class you see the 'Imports', they tell what libraries are used (even though I don't understand why System.Windows.Forms is imported for a console application, oh nevermind..). The one that slips all WMI beginners using copied code is the Imports System.Management, you then get this error:
VB2005:
Warning 1 Namespace or type specified in the Imports 'System.management' doesn't contain any public member or cannot be found.

VB2003:
Namespace or type 'management' for the Imports 'System.management' cannot be found.
You will then use the Add Reference dialog (from main menu 'Project' or by context menu) and browse the .Net tab to System.Management and add it.

Also, do remember to set Code Language in Code Creator to VB.Net, default is VB Script :):)
 
Dear Mr. John,

I am sorry to bother you after the detailed explanation provided by you. I am stuck at something very basic (I know) and I understand that you expect me to know more to be able to use the code.

While try to begin exploiting the mechanism, I have tried to plant the following piece of code in my program. Here, I do not know what is the declaration I need to provide for the variables objWMIService, colItems and objItem. Further, I think I need to explore why we need to create that loop. I want to look for the disk space available on a single disk and possibly I can programatically determine the disk I want to enquiry.

VB.NET:
Private Sub UpdateDiskStatus()
Dim l_strComputer As String
Dim l_objWMIService As WMIService
l_strComputer = "."
l_objWMIService = GetObject("winmgmts:\\" & l_strComputer & "\root\CIMV2")
l_colItems = l_objWMIService.ExecQuery("SELECT * FROM Win32_DiskDrive", , 48)
For Each l_objItem In l_colItems
Wscript.Echo("-----------------------------------")
Wscript.Echo("Win32_DiskDrive instance")
Wscript.Echo("-----------------------------------")
Wscript.Echo("Availability: " & l_objItem.Availability)
Next
End Sub

I would be extremely grateful for your kind reply and patience.

Regards,
 
Partham, you might give this a go if you are working in a WindowsXP or newer environment:

VB.NET:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim myCounter As System.Diagnostics.PerformanceCounter = New System.Diagnostics.PerformanceCounter
        myCounter.CategoryName = "LogicalDisk"
        myCounter.CounterName = "% Free Space"
        myCounter.InstanceName = "C:"

        MessageBox.Show(FormatNumber(myCounter.NextValue, 2) & "% Free")
    End Sub

PerformanceCounters are great and simpler than WMI (I think) for what you are wanting, but I don't think the LogicalDisk one was available Pre-XP.
 
partam , you need to switch 'Code Language' in that program to VB.NET, what you posted is VBscript. You can also click the 'Execute Code' button to see the output, that will give you a better understanding of what's going on looping and all. Clicking the 'Get documentation..' link will give you help about each property and class. The program is helpful for generating much code that is often the same and also for beginner to get started with a basic thing, but more knowledge will give you more power to change the generated code to exactly what you need. There are plenty of WMI tutorials out there too if you find it interesting.
 
Dear Mr. John,

Thanks you very much for your help. I have formulated a class with necessary methods (one of which I have included below).

VB.NET:
Public Shared Function GetTotalDiskSpace(ByVal strDriveName As String) As UInt64
Dim l_objSearcher As ManagementObjectSearcher
Dim l_uintReturnValue As UInt64
Dim l_strDeviceID As String
Dim l_bDriveFound As Boolean = False
Try
strDriveName = AssignNotNullStringValue(strDriveName)
l_objSearcher = New ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_LogicalDisk")
For Each l_objQuery As ManagementObject In l_objSearcher.Get()
If strDriveName.Equals(CType(l_objQuery("DeviceID"), String)) Then
l_bDriveFound = True
l_uintReturnValue = l_objQuery("Size")
End If
Next
If Not l_bDriveFound Then Throw New InvalidDriveProvidedException
Catch ex As ManagementException
Throw ex
End Try
Return l_uintReturnValue
End Function

Now, I am faced with a difficulty. The value returned is a UInt64 and I cannot convert it to Integer or Long or perform any operations like /, etc. This is making it difficult for me program further where I would like to provide some visual interface.

Dear Mr. Raven,
Thank you for the input. I will try the method suggested as well. One of the difficulty I am faced using the WMI code is that it check all the drives on the system everytime the function is called, which is not very desirable. Especially, it kills time when it accesses the floppy drive and the CD ROM drive as well. I have to check if it also accesses the mapped drives.

In your suggestion, what are the constants for "Total Disk Space" and "Free Disk Space". "% Free Space" gives the percentage free. I would also like to know the actual amount of space free.


I remain grateful for the help I have already received.

Regards,
:) :) :) :) :) :)
 
Dear Sir,

I have worked out the mechanism to use the UInt64 structure. I am able to get the string equivalent using the ToString method and then I can convert the string to Long.

Regards,
Partha.
 
In case you wish to continue on the PerformanceCounter side to avoid the other problem you mentioned:

There dosen't appear to be a total space counter. There is one for "Free Megabytes" and the "% Free Space" so my approach would be to get total size by working reverse from those two.

TotalSpace = (MegabytesFree * 100)/%FreeSpace (if I remember my algebra right)
 
Dear Mr. Raven,

Thanks for the input.

I am using the Performance Counter. This is because I have to continuously find out the disk status (in short intervals) and raise alerts (by mail or SMS) whenever the disk space reaches a critical level. Querying using WMI may cause the Floppy Drive, especially, to go bad after some time (I suppose).

However, I am now exposed to some awfully wonderful avenues.

Thanks a ton to both Mr. John and yourself for the same.

Regards,
Partha.
 
System.Convert class also support conversion from UInt64.

I don't think floppy drive (which I actually still got one of too:)) will go bad from polling, in the ancient days of computing the floppy drive was pretty much polling like that all the time and they rarely failed, but I know what you mean it's annoying (and slow).

Another fantastic possibility with WMI is to subscribe to your custom made events. For you as beginner I would say this is too advanced, but know there exist such functionality! Similar to Monitoring Free Disk Space in Real-Time and Sending E-mail Based on an Event or other example you may find from internet (I found those two articles when searching for "wmi event low disk space" there should be lots more examples) you can too with some fiddling work get a code start from the "Receive an event" tab in WMI Code Creator. As I said, I will not recommend this for beginner, but knowing it can be done you might delve back into WMI Events when you are more more confident in VB.Net programming and WMI in general.
 
Dear Mr. John,

I will definitely delve into the links provided by you.

In the meanwhile, I have found a way to work around the problem that I stated yesterday regarding the Floppy Drive. (It did not strike me yesterday possibly because it was very late in the night). The altered code is as follows:

VB.NET:
l_objSearcher = New ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_LogicalDisk WHERE DeviceID = '" + strDriveName + "'")

I expect this to work. Please let me know whether this is okay.

Regards,
 
Back
Top