Recursive File Count Function

Here's a simple recursive function for counting all the files in a given folder and its subfolders. Be careful... it might take a while if you run it as-is. I declare the count in the test-harness, and set the parameter passed in as “ByRef“, so that it increments the counter that lives in the test-harness. It's much better than passing it back and forth, because with the recursive you don't know how many times a new copy of the variable would be created.

Private Sub Test()
    Dim fileCount As Integer = 0
    Dim Dir As New System.IO.DirectoryInfo("c:\")
    RecursiveCount(Dir, fileCount)
End Sub

Private Sub RecursiveCount(ByVal theDir As DirectoryInfo, ByRef Count As Integer)
    Dim subDirectories() As DirectoryInfo = theDir.GetDirectories
    For i As Integer = 0 To subDirectories.Length - 1
        Dim subFiles() As FileInfo = subDirectories(i).GetFiles
        Count += subFiles.Length
        Debug.Write(subDirectories(i).FullName & Chr(13))
        RecursiveCount(subDirectories(i), Count)
    Next
End Sub

Another hour and I'll be finished with the function to recreate the new linked directories for CarbonCopy.NET. It's kind of complicated, because you have to recreate a new directory structure from a different root. I think I have it about down though. We'll see in about an hour.

2 Comments

  • Sounds like you are re-writing System.IO.Directory.CreateDirectory() which says: "Remarks

    Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid."

  • Um..... no. Like I said, I was working on a different program, and comparing two different directories, and combining information to get a new directory structure. It was string manipulation, not re-creating the CreateDirectory function.

Comments have been disabled for this content.