Determining the Size of a Directory Without Using FileSystemObject

P

Phil Galey

Using the following, you can determine the size of a file:

Dim fi As New IO.FileInfo(<Path to file>)
MsgBox(fi.Length)

.... but what about the size of a directory? The IO.DirectoryInfo object
doesn't have a Length property.
In is there a way in VB.NET to determine the size of a directory without
having to resort to importing the Scripting DLL and using the
FileSystemObject? Thanks.
 
G

Guest

Hi Phil,

Here is one way you can do it, but it's not a recursive directory size:

Private Function DirectorySize(ByVal sDir As String) As Long
Dim d As New IO.DirectoryInfo(sDir)
Dim fils As IO.FileInfo() = d.GetFiles()
Dim f As IO.FileInfo
Dim i As Integer
For Each f In fils
i += f.Length
Next
Return i
End Function

Usage:
--------

' Directory to check for size
Dim strDir As String =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
' Variable to convert direct size into bytes
Dim intBytes As Int32 = DirectorySize(strDir)
' Variable to convert direct size into kilobytes
Dim intKiloBytes As Int32 = (DirectorySize(strDir) \ 1024)
' Variable to convert direct size into megabytes
Dim intMegaBytes As Int32 = (DirectorySize(strDir) \ 1048576)
' Variable to convert direct size into gigabytes
Dim intGigaBytes As Int32 = (DirectorySize(strDir \ 1073741824))
' Show results in bytes
MessageBox.Show(String.Format("The directory size is {0:d2} bytes",
intBytes))
' Show results in kilobytes
MessageBox.Show(String.Format("The directory size is {0} KB",
intKiloBytes))
' Show results in megabytes
MessageBox.Show(String.Format("The directory size is {0} MB",
intMegaBytes))
' Show results in gigabytes
MessageBox.Show(String.Format("The directory size is {0} Gb",
intGigaBytes))

I hope this helps
 
G

Guest

I decided to code you a recursive directory size function:

Public Shared Function GetDirectorySize(ByVal sPath As String) As Long
Dim lngSize As Long = 0
Dim diDir As New System.io.DirectoryInfo(sPath)
Dim fil As System.io.FileInfo
For Each fil In diDir.GetFiles()
lngSize += fil.Length
Next fil
' Recursively call the function
Dim subDirInfo As System.io.DirectoryInfo
For Each subDirInfo In diDir.GetDirectories()
lngSize += GetDirectorySize(subDirInfo.FullName)
Next subDirInfo
Return lngSize
End Function

Usage:
--------

Dim strDir As String =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
MessageBox.Show(GetDirectorySize(strDir))

The above example will get the directory size of the Desktop including all
sub directories.

If you use the conversions from my other post, you can soon put the info
into bytes, kilobytes, megabytes & gigabytes

I hope this helps
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top