Vb.Net: Recursive File Count


Function CountFiles(ByVal Directory As String) As Integer
'Recursive File Counter
'by Derek Anderson
'dim variables
Dim FileCount As Integer = 0
Dim SubDirectory() As String
Dim i As Integer

'get the count of files in the current directory
FileCount = System.IO.Directory.GetFiles(Directory).Length
'get a list of sub directories from current directory
SubDirectory = System.IO.Directory.GetDirectories(Directory)

'for ever sub directory, count the files and add to file count
'this is a recursive routine, so it will call this again and
'return the file count of every directory, and add it to the file
'count originally started
For i = 0 To SubDirectory.Length - 1
FileCount = CountFiles(SubDirectory(i)) + FileCount
Next

Return FileCount

End Function

5 comments.

  1. your site provided us a lot of
    desired info on that post.
    The message really desired.

  2. Hi

    Is their a way to change the code so it displays the file count for each directory to a list box.

    Example:
    c:\test = 0
    c:\test\dirt1 = 17
    c:\test\ddd = 6

    Thanks

  3. It could easily be changed, but this is a really simple example of the a recursive version.You can publish CountFiles()and SubDirectory() to the list box as the name and the count of files.

    ListBox.Add SubDirectory(i) & ” - ” & CountFiles(SubDirectory(i))

  4. Thanks a lot!

  5. Thanks. Very helpful.

Post a comment.