Solved

Problems calculating total directory size inclusive of files and sub directories

Posted on 2007-04-11
11
280 Views
Last Modified: 2010-04-23
I am using the following function to calculate TOTAL directory size, inclusive of sub directories and files.
I works for all of the files within the main directory, but then resets when it goes to the first sub directory.

Can anyone see where it is going wrong and how it can be fixed.

Thanks,
Michael

    Function GetFolderSize(ByVal DirPath As String, Optional ByVal IncludeSubFolders As Boolean = True) As Long

        Dim lngDirSize As Long
        Dim objFileInfo As FileInfo
        Dim objDir As DirectoryInfo = New DirectoryInfo(DirPath)
        Dim objSubFolder As DirectoryInfo

        Try
            'add length of each file
            For Each objFileInfo In objDir.GetFiles()
                lngDirSize += objFileInfo.Length
            Next
            'call recursively to get sub folders
            'if you don't want this set optional
            'parameter to false
            If IncludeSubFolders = True Then
                For Each objSubFolder In objDir.GetDirectories()
                    lngDirSize += GetFolderSize(objSubFolder.FullName)
                Next
            End If
        Catch Ex As Exception
        End Try
        If lngDirSize > 0 Then
            Return BytesToMegabytes(lngDirSize)
        Else
            Throw New Exception("Invalid or unreadable directory")
            Exit Function
        End If
    End Function

    Private Function BytesToMegabytes(ByVal Bytes As Long) _
    As Long
        Dim dblAns As Double
        dblAns = (Bytes / 1024) / 1024
        BytesToMegabytes = Format(dblAns, "###,###,##0.00")
    End Function

It is being called with:

TotalData = GetFolderSize("c:\temp\", True)
0
Comment
Question by:webkiwi1
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
  • 3
11 Comments
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 18892513
This value of Dim lngDirSize As Long is getting rest to 0 each time the function GetFolderSize is called. Pass in the value of lngDirSize to the function and the first time you call it pass in 0.
0
 

Author Comment

by:webkiwi1
ID: 18892541
I understand what you are saying, how would I pass in the value?
0
 
LVL 11

Expert Comment

by:Babycorn-Starfish
ID: 18892589
Would the call to BytesToMegaBytes towards the bottom of your function affect things too if you're calling it recursively and adding the results together? You're essentially working with two different scales, if this is right call this on the overal result of GetFolderSize
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:webkiwi1
ID: 18892680
Another good point Babycorn-Starfish (?!?!?!)

Perhaps I should move the call to MytesToMegaBytes from the GetFolderSize function to the page load sub.
0
 
LVL 11

Accepted Solution

by:
Babycorn-Starfish earned 250 total points
ID: 18892683
hi try this,


    Sub Main()
        Dim totalSize As Long = GetFolderSize("d:\New Folder", True)
        Console.Write("" + BytesToMegabytes(totalSize).ToString())
        Console.Read()
    End Sub

    Function GetFolderSize(ByVal DirPath As String, Optional ByVal IncludeSubFolders As Boolean = True) As Long
        Dim lngDirSize As Long
        Dim objFileInfo As IO.FileInfo
        Dim objDir As IO.DirectoryInfo = New IO.DirectoryInfo(DirPath)
        Dim objSubFolder As IO.DirectoryInfo

        Try
            'add length of each file
            For Each objFileInfo In objDir.GetFiles()
                lngDirSize += objFileInfo.Length
            Next
            'call recursively to get sub folders
            'if you don't want this set optional
            'parameter to false
            If IncludeSubFolders = True Then
                For Each objSubFolder In objDir.GetDirectories()
                    lngDirSize += GetFolderSize(objSubFolder.FullName)
                Next
            End If
        Catch Ex As Exception
        End Try
        GetFolderSize = lngDirSize
    End Function

    Private Function BytesToMegabytes(ByVal Bytes As Long) As Double
        Dim dblAns As Double
        dblAns = (Bytes / 1024) / 1024
        BytesToMegabytes = dblAns 'Format(dblAns, "###,###,##0.00")
    End Function
0
 
LVL 11

Expert Comment

by:Babycorn-Starfish
ID: 18892700
comment or uncomment the Format bit depending on what you need. You may want to round it up or down depending on how accurate you need it too
0
 
LVL 11

Expert Comment

by:Babycorn-Starfish
ID: 18892713
Sorry, left my file path in there !
0
 
LVL 63

Assisted Solution

by:Fernando Soto
Fernando Soto earned 250 total points
ID: 18892831
   Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click

        Dim TotalData As Long = GetFolderSize("C:\Temp\MSPress\Crystal_Reports_10\", 0, True)

    End Sub

    Function GetFolderSize(ByVal DirPath As String, ByVal dirSize As Long, _
        Optional ByVal IncludeSubFolders As Boolean = True) As Long

        Dim lngDirSize As Long = dirSize
        Dim objFileInfo As FileInfo
        Dim objDir As DirectoryInfo = New DirectoryInfo(DirPath)
        Dim objSubFolder As DirectoryInfo

        Try
            'add length of each file
            For Each objFileInfo In objDir.GetFiles()
                lngDirSize += objFileInfo.Length
            Next
            'call recursively to get sub folders
            'if you don't want this set optional
            'parameter to false
            If IncludeSubFolders = True Then
                For Each objSubFolder In objDir.GetDirectories()
                    lngDirSize += GetFolderSize(objSubFolder.FullName, lngDirSize)
                Next
            End If
        Catch Ex As Exception
        End Try

        Return lngDirSize

        ' You do not want to do this here, you want to do it once ater the initial call
        'If lngDirSize > 0 Then
        '    Return BytesToMegabytes(lngDirSize)
        'Else
        '    Throw New Exception("Invalid or unreadable directory")
        '    Exit Function
        'End If
    End Function

    Private Function BytesToMegabytes(ByVal Bytes As Long) _
    As Long
        Dim dblAns As Double
        dblAns = (Bytes / 1024) / 1024
        BytesToMegabytes = Format(dblAns, "###,###,##0.00")
    End Function
0
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 18892847
Change my file path in my last post
0
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 18892922
Hi webkiwi1;

As I stated in my post above you want to convert the bytes to megabytes at the very end and not after each directory is completed being tallied up. Also the exception you are throwing is not really true, "Invalid or unreadable directory", because directory info only returns valid names. Also a directory may have no files in it and will have zero bytes returned which does not make it a invalid directory.

       If lngDirSize > 0 Then
           Return BytesToMegabytes(lngDirSize)
       Else
           Throw New Exception("Invalid or unreadable directory")
           Exit Function
       End If

Fernando
0
 

Author Comment

by:webkiwi1
ID: 18893279
Got both to work. For some reason the calculated value using Fernado's was off somewhere, but function still worked. Thanks guys for the fast and accurate responses.
0

Featured Post

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entering a date in Microsoft Access can be tricky. A typo can cause month and day to be shuffled, entering the day only causes an error, as does entering, say, day 31 in June. This article shows how an inputmask supported by code can help the user a…
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…

724 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question