obtaining the size of a directory object

inzo21

Well-known member
Joined
Nov 5, 2003
Messages
74
Hello all,

Sometimes I hate programming - usually when I run out of beer! Today is that day!

Anyway, I need to be able to obtain the size of a directory on the file system without having to iterate through all subdirectories, calculate the file sizes, tally them and then produce a result.

I tried the following to no avail.

Dim tmpdirinfo As DirectoryInfo = New DirectoryInfo(dirname)
dirlength = tmpdirinfo.GetFileSystemInfos.LongLength

I get a result - but it is not the size of the directory. I tried researching this on MSDN, various other websites and numerous books - they all are not specific enough about the GetFileSystemInfos subclass - arghhh.

Any help would be appreciated. Thanks again...

inzo
 
if you really dont want to loop through the files and folders in a directory , you could ( and this isnt really the vb.net way to go ) use the filesystem object . heres a quick example i knocked up for you...
Code:
        Dim path As Object() = {Environment.GetFolderPath(Environment.SpecialFolder.Personal)}
        Dim fso As Object = CreateObject("Scripting.FileSystemObject")
        Dim f As Object = fso.GetType.InvokeMember("GetFolder", Reflection.BindingFlags.InvokeMethod, Nothing, fso, path)
        Dim objSize As Object = f.GetType.InvokeMember("Size", Reflection.BindingFlags.GetProperty, Nothing, f, Nothing)

        Dim strSize As String = Convert.ToString(objSize)

        MessageBox.Show(strSize & " is the size in bytes!")
 
got it - thanks

Thanks Sysop.

That worked. In the meantime I was using the following function that I found on MSDN to get the same result. I figured I would post it here in case anyone was reading and needed to do this.

Private Function DirSize(ByVal d As DirectoryInfo) As Long
Dim Size As Long = 0
Add file sizes.
Dim fis As FileInfo() = d.GetFiles()
Dim fi As FileInfo
For Each fi In fis
Size += fi.Length
Next fi
Add subdirectory sizes.
Dim dis As DirectoryInfo() = d.GetDirectories()
Dim di As DirectoryInfo
For Each di In dis
Size += DirSize(di)
Next di
Return Size
End Function DirSize

It calculates the size of all files in all directories passed to it without minimal overhead. Actually, the seek time was about the same as the solution you provided - suprisingly. I guess .Net has improved on performance a little more than VB6.

Thanks again and have a great day.

inzo
 
Back
Top