Wednesday, August 12, 2009

How to find the size of a Directory

nd the size of a Directory



Working with files and
directories is one of my favorites! With the help of the namespace, System.IO we can parse through the entire hard disk of our
computer. The System.IO namespace has rich inbuilt
methods/functions for every common task that we need to do. With the help of
these functions, we can easily write code for:



Does this file exist?

What is the size of this file?

Delete this file

Get all files in this directory ... and so on.



But the said namespace or other namespace does not provide us with a function
which gives the directory size. One way to find the directory size of any
folder/directory is as follows:



1) Start from the directory/folder that we need to find the size

2) Find all files in the current directory

3) Loop through each file and find the size of
each file

4) Chances are, we may end up with sub-folders.

5) We also need to find the number of files in this sub-folder

6) Since this is a repeating process, we should have a recursive mechanism were
we will parse through the end (until no more sub-directories exists)



The following example consists of three functions. A) Public DirectorySize(ByVal strStartDirectory as String)

B) Private FindDirectorySize(ByVal
strCurrentDir As String)

C) Private Sub RecursiveParseDirectory(ByVal strDirectory As String)



Include all the three functions in aspx or codebehind page and invoke the function, DirectorySize. Pass the folder/directory name as an
argument to this method and it will return you the size of the directory. You
will also need to declare a global variable called: intDirectorySize
which is of type, Integer.








Dim intDirectorySize As Integer



Public Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

' For this example, I have used "." which represents the current
directory



lblMsg.Text =
"Directory size is " & DirectorySize(".")

End Sub



Public Function DirectorySize(ByVal
strStartDir As String)

Dim strStartDirectory
As String = Server.MapPath(strStartDir)



FindDirectorySize(strStartDirectory)

RecursiveParseDirectory(strStartDirectory)



Return intDirectorySize

End Function



Private Sub RecursiveParseDirectory(ByVal strDirectory As String)

Dim strTemp As String

Dim arrSubDirectories()
As String = Directory.GetDirectories(strDirectory)



For Each strTemp In arrSubDirectories

FindDirectorySize(strTemp)

RecursiveParseDirectory(strTemp)

Next

End Sub



Private Sub FindDirectorySize(ByVal
strCurrentDir As String)

Dim DI As DirectoryInfo
= New DirectoryInfo(strCurrentDir)

Dim arrFiles As Array
= DI.GetFiles()

Dim FI As FileInfo

Dim intDirsize As
Integer = 0



For Each FI In arrFiles

intDirsize += FI.Length

Next



intDirectorySize += intDirsize

End Sub











0 comments:

Post a Comment