Reading free drive space

robo100

Member
Joined
Dec 13, 2005
Messages
14
Location
New Mexico
Programming Experience
3-5
Is there an easy way to read free hard disk space? I have an application where I want to warn the user that the hard drive is getting full.
 
WMI is one way, Win32 API is another, FileSystemObject from scripting is yet another.
Here is a fast WMI query to check free space on logical disk C:
VB.NET:
Dim disk As New ManagementObject("win32_logicaldisk.deviceid=""c:""")
disk.Get()
MsgBox(disk("FreeSpace").ToString())
Here is another, getting all local non-removable disks space and free space:
VB.NET:
Dim moSearch As New ManagementObjectSearcher("Select * from Win32_LogicalDisk")
Dim myCollection As ManagementObjectCollection = moSearch.Get()
Dim msg As String = ""
For Each WmiObject As ManagementObject In myCollection
If WmiObject("DriveType") = 3 Then 'local disk, non-removable
msg += WmiObject("DeviceID") _
& " " & WmiObject("FreeSpace") _
& " free of " & WmiObject("Size") & vbCrLf
End If
Next
MsgBox(msg)
(add reference to system.management and Imports System.Management)
 
Here is the same using scripting object. Add reference to Microsoft Scripting Runtime from COM list first.
VB.NET:
Dim msg As String = ""
Dim fso As New Scripting.FileSystemObject
Dim drv As Scripting.Drive
For Each drv In fso.Drives
If drv.IsReady And drv.DriveType = Scripting.DriveTypeConst.Fixed Then
msg += drv.DriveLetter _
& " " & drv.FreeSpace _
& " free of " & drv.TotalSize & vbCrLf
End If
Next
MsgBox(msg)
 
Getting updated, .Net 2.0 has got a new class System.IO.DriveInfo where you can find the same info.
A shortcut for this is also My.Computer.FileSystem.GetDriveInfo for instance.
 
I found this thread. i can get all this to work but i would like it to do a few more things for me.

I would like it to show the percentage left as well. i.e. c: = 34% free
and also i would like to pick on computer on the network.

is this possible?
 
Percentage is the calculation of freespace*100/totalspace.
If network drive is mapped to a local driveletter it will be in the drives collection too.
 
For the percentage you can just work it out yourself....

Get the total drive size.. say 20000 Mb (20 gig)
Get the remaining space... 5000 Mb (5 gig)

remaining space/total size *100 =

voila - 25%
 
This post was a big help to me, as I was converting a VB6 project that used the "GetDiskFreeSpace" API to get this info. Anyway, as a small contribution, here is a function that may save someone else a little extra time:

VB.NET:
   Function GetDiskPctFree(ByVal lsDriveLtr As String) As Single
      Static lnPctFree As Single = 0
      Dim di As System.IO.DriveInfo
      di = My.Computer.FileSystem.GetDriveInfo(lsDriveLtr)
      If di.IsReady Then
         If di.AvailableFreeSpace > 0 Then
            lnPctFree = (di.AvailableFreeSpace / di.TotalSize) * 100
         End If
      End If
      Return lnPctFree
   End Function

Thanks again for this helpful information.
 
Back
Top