Solved

Non-recursive function in finding folder and subfolder size

Posted on 2002-04-08
14
448 Views
Last Modified: 2011-09-20
Below is the coding in finding the size of the folder and subfolder size using recursive function SizeOf. However I encounter "Overflow Stack " problem. Therefore I would like to get this function to be rewritten but using non-recursive way. I don't want to use fso object. Anyone can help?

 Const MAX_PATH = 260
 Type FILETIME
    dwLowDateTime As Long
    dwHighDateTime As Long
End Type

 Type WIN32_FIND_DATA
    dwFileAttributes As Long
    ftCreationTime As FILETIME
    ftLastAccessTime As FILETIME
    ftLastWriteTime As FILETIME
    nFileSizeHigh As Long
    nFileSizeLow As Long
    dwReserved0 As Long
    dwReserved1 As Long
    cFileName As String * MAX_PATH
    cAlternate As String * 14
End Type

Declare Function FindFirstFile Lib "kernel32" _
Alias "FindFirstFileA" (ByVal lpFileName As String, _
lpFindFileData As WIN32_FIND_DATA) As Long

Declare Function FindNextFile Lib "kernel32" _
Alias "FindNextFileA" (ByVal hFindFile As Long, _
lpFindFileData As WIN32_FIND_DATA) As Long

Declare Function FindClose Lib "kernel32" _
(ByVal hFindFile As Long) As Long


Public Function SizeOf(ByVal DirPath As String) As Double
    Dim hFind As Long
    Dim fdata As WIN32_FIND_DATA
    Dim dblSize As Double
    Dim sName As String
    Dim x As Long

On Error Resume Next

     
    x = GetAttr(DirPath)
 
    If Err Then SizeOf = 0: Exit Function
   
     If (x And vbDirectory) = vbDirectory Then
        dblSize = 0
        Err.Clear
        sName = Dir$(EndSlash(DirPath) & "*.*", vbSystem Or vbHidden Or vbDirectory)
       
        If Err.Number = 0 Then
        hFind = FindFirstFile(EndSlash(DirPath) & "*.*", fdata)
       
            If hFind = 0 Then Exit Function
                Do
                    MsgBox fdata.cFileName
                    If (fdata.dwFileAttributes And vbDirectory) = vbDirectory Then
                        sName = Left$(fdata.cFileName, InStr(fdata.cFileName, vbNullChar) - 1)
                     
                            If sName <> "." And sName <> ".." Then
                                                           dblSize = dblSize + SizeOf(EndSlash(DirPath) & sName)
                            End If
                    Else
                        dblSize = dblSize + fdata.nFileSizeHigh * 65536 + fdata.nFileSizeLow
                    End If
                    DoEvents
                Loop While FindNextFile(hFind, fdata) <> 0
                    hFind = FindClose(hFind)
            End If
        Else
        On Error Resume Next
        dblSize = FileLen(DirPath)
    End If
    SizeOf = dblSize
         
End Function

0
Comment
Question by:MarcusAu
  • 5
  • 3
  • 3
  • +2
14 Comments
 
LVL 49

Expert Comment

by:Ryan Chong
Comment Utility
Hi MarcusAu,

Similar but different example:

http://www.mvps.org/vbnet/code/fileapi/getdirectorysize.htm

Hope this help
0
 

Author Comment

by:MarcusAu
Comment Utility
ryancys,
I'm glad you gave an example.However, it still doesn't provide a solution to my problem. It should  return the size of all the subfolders without using recursive function.
0
 

Author Comment

by:MarcusAu
Comment Utility
ryancys,
I'm glad you gave an example.However, it still doesn't provide a solution to my problem. It should  return the size of all the subfolders without using recursive function.
0
 
LVL 18

Expert Comment

by:mdougan
Comment Utility
You need to reference the Microsoft Scripting Runtime, and then try this code:

Private Sub Command1_Click()
Dim oFileSysObj As Scripting.FileSystemObject
Dim oFolder As Scripting.Folder
Dim dblDirSize As Double
   
    Me.Cls
   
    Set oFileSysObj = New Scripting.FileSystemObject
    Set oFolder = oFileSysObj.GetFolder("C:\Winnt")
    dblDirSize = oFolder.Size
   
    Me.Print Format((dblDirSize + 1) / 1000, "###,###,###,##0") & "KB"
End Sub
0
 

Author Comment

by:MarcusAu
Comment Utility
mdougan,
Thanks for your suggestion but as I said I do not want to use fso(file system object) because it has memory problem.
0
 
LVL 18

Expert Comment

by:mdougan
Comment Utility
Sorry, I missed the fso comment.  Well, if you don't want to use recursion, and you don't want to use fso, then you might be SOL ;)
0
 
LVL 2

Expert Comment

by:mbenassor
Comment Utility
To use this code I wrote you will need to have FileListBox and DirListBox objects on your Form - you can set them to invisible so they wont get in the way.



Public Function FolderSize(folder As String, FLBox As FileListBox, DLBox As DirListBox) As Long
    Dim colFolders As Collection, i As Long, lngSize As Long
    Dim add As Long
   
    Set colFolders = New Collection
    colFolders.add (folder)
   
    While colFolders.Count > 0
        With FLBox
            .Path = colFolders.Item(1)
            For i = 0 To .ListCount
                If .List(i) <> "" Then
                    lngSize = lngSize + FileLen(.Path & "\" & .List(i))
                End If
            Next
        End With
   
        With DLBox
            .Path = colFolders.Item(1)
            colFolders.Remove (1)
            For i = 0 To .ListCount
                If .List(i + add) <> "" Then
                    colFolders.add (.List(i))
                End If
            Next
        End With
    Wend
    FolderSize = lngSize
End Function
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 2

Expert Comment

by:mbenassor
Comment Utility
Please ignore my prev. function - it fails when folder size is larger than 2GB, fixed function will work properly.

Public Function FolderSize(folder As String, FLBox As FileListBox, DLBox As DirListBox) As Variant
    Dim colFolders As Collection, i As Long, vSize As Variant
   
    Set colFolders = New Collection
    colFolders.add (folder)
   
    While colFolders.Count > 0
        With FLBox
            .Path = colFolders.Item(1)
            For i = 0 To .ListCount
                If .List(i) <> "" Then
                    vSize = vSize + FileLen(.Path & "\" & .List(i))
                End If
            Next
        End With
   
        With DLBox
            .Path = colFolders.Item(1)
            colFolders.Remove (1)
            For i = 0 To .ListCount
                If .List(i) <> "" Then
                    colFolders.add (.List(i))
                End If
            Next
        End With
    Wend
    FolderSize = vSize
End Function
0
 

Author Comment

by:MarcusAu
Comment Utility
Frankly speaking, I am trying to use the code for vb script. However , vb script does not support collection. Therefore, I am trying to find a way to write a function without using recursive, fso and collection.
0
 
LVL 2

Expert Comment

by:mbenassor
Comment Utility
VBScript supports DirListBox and FileListBox ?
If so , this code should work :


Public Function FolderSize(folder As String, FLBox As FileListBox, DLBox As DirListBox) As Variant
   Dim sFolders() As String, lFolders As Long, i As Long, vSize As Variant
   
   lFolders = 1
   ReDim sFolders(1 To 10) As String
   sFolders(lFolders) = folder
   
   While lFolders > 0
       With FLBox
           .Path = sFolders(lFolders)
           For i = 0 To .ListCount
               If .List(i) <> "" Then
                   vSize = vSize + FileLen(.Path & "\" & .List(i))
               End If
           Next
       End With
   
       With DLBox
           .Path = sFolders(lFolders)
           lFolders = lFolders - 1
           For i = 0 To .ListCount
               If .List(i) <> "" Then
                    lFolders = lFolders + 1
                    If lFolders > UBound(sFolders) Then
                        ReDim Preserve sFolders(1 To UBound(sFolders) * 2) As String
                    End If
                    sFolders(lFolders) = .List(i)
               End If
           Next
       End With
   Wend
   FolderSize = vSize
End Function

0
 

Author Comment

by:MarcusAu
Comment Utility
I'm sorry to tell you VB script does not support DirListBox and FileListBox object. Appreciate your effort very much in helping me.
0
 
LVL 1

Expert Comment

by:Moondancer
Comment Utility
ADMINISTRATION WILL BE CONTACTING YOU SHORTLY.  Moderators Computer101, Netminder or Mindphaser will return to finalize these if they are still open in 7 days.  Experts, please post closing recommendations before that time.

Below are your open questions as of today.  Questions which have been inactive for 21 days or longer are considered to be abandoned and for those, your options are:
1. Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you, but may help others. You must tell the participants why you wish to do this, and allow for Expert response.  This choice will include a refund to you, and will move this question to our PAQ (Previously Asked Question) database.  If you found information outside this question thread, please add it.
3. Ask Community Support to help split points between participating experts, or just comment here with details and we'll respond with the process.
4. Delete the question (if it has no potential value for others).
   --> Post comments for expert of your intention to delete and why
   --> YOU CANNOT DELETE A QUESTION with comments; special handling by a Moderator is required.

For special handling needs, please post a zero point question in the link below and include the URL (question QID/link) that it regards with details.
http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt
 
Please click this link for Help Desk, Guidelines/Member Agreement and the Question/Answer process.  http://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp

Click you Member Profile to view your question history and please keep them updated. If you are a KnowledgePro user, use the Power Search option to find them.  

Questions which are LOCKED with a Proposed Answer but do not help you, should be rejected with comments added.  When you grade the question less than an A, please comment as to why.  This helps all involved, as well as others who may access this item in the future.  PLEASE DO NOT AWARD POINTS TO ME.

To view your open questions, please click the following link(s) and keep them all current with updates.
http://www.experts-exchange.com/questions/Q.20099164.html
http://www.experts-exchange.com/questions/Q.20100105.html
http://www.experts-exchange.com/questions/Q.20129810.html
http://www.experts-exchange.com/questions/Q.20174336.html
http://www.experts-exchange.com/questions/Q.20285962.html



*****  E X P E R T S    P L E A S E  ******  Leave your closing recommendations.
If you are interested in the cleanup effort, please click this link
http://www.experts-exchange.com/jsp/qManageQuestion.jsp?ta=commspt&qid=20274643
POINTS FOR EXPERTS awaiting comments are listed in the link below
http://www.experts-exchange.com/commspt/Q.20277028.html
 
Moderators will finalize this question if in @7 days Asker has not responded.  This will be moved to the PAQ (Previously Asked Questions) at zero points, deleted or awarded.
 
Thanks everyone.
Moondancer
Moderator @ Experts Exchange
0
 
LVL 18

Expert Comment

by:mdougan
Comment Utility
Well, no one answered the question given the Questioner's restrictions.  However, there is good info here for someone with more reasonable requirements.  I'd suggest reducing the points to zero and closing it out as a PAQ
0
 
LVL 1

Accepted Solution

by:
Moondancer earned 0 total points
Comment Utility
Thank you, 150 points refunded, question moved to our PAQ at zero points and closed.
Moondancer - EE Moderator
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

The debugging module of the VB 6 IDE can be accessed by way of the Debug menu item. That menu item can normally be found in the IDE's main menu line as shown in this picture.   There is also a companion Debug Toolbar that looks like the followin…
This article describes some techniques which will make your VBA or Visual Basic Classic code easier to understand and maintain, whether by you, your replacement, or another Experts-Exchange expert.
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…

771 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now