简体   繁体   中英

Recursively Counting Files in Folders and Subfolders Including Root VB.NET

I am trying to count the total number of files in folders and subfolders in CDROM drive F:\\ The total number of files on the CDROM is 58 but the total file count returned by my code below is 39. All 39 files counted are contained in folders and the missing 19 files are in the root of drive F:\\

How can I count the files in the root as well as the folders \\ subfolders?

I am using a recursive search as I found it works better with Try\\Catch exception errors than IO.Directory.EnumerateFiles(DirectoryPath, "*", IO.SearchOption.AllDirectories).Count etc.

Regards

Georgy

Public Sub Search1()

    Dim DirectoryPath = TextBox1.Text
    Dim TotalFileCount As Long = 0

    Search2(DirectoryPath, TotalFileCount)
    MsgBox(TotalFileCount)

End Sub

Public Sub Search2(ByVal DirectoryPath As String, ByRef TotalFileCount As Integer)

    Dim FileName As String = Nothing

    Try
        For Each Directory In IO.Directory.GetDirectories(DirectoryPath)
            For Each File In IO.Directory.GetFiles(Directory, "*")
                FileName = New IO.FileInfo(File).FullName
                TotalFileCount += 1
            Next
            Search2(Directory, TotalFileCount)
        Next
    Catch ua As UnauthorizedAccessException
        ListBox1.Items.Add("Exception: " & ua.Message & " " & FileName)
    Catch ex As Exception
        ListBox1.Items.Add("Exception: " & ex.Message & " " & FileName)
    End Try
End Sub

In your Search2 method you should find files outside the foreach loop of directories. Your method is looking for subfolders and files inside these folders but not files inside the current folder.

Try this

Public Sub Search2(ByVal DirectoryPath As String, ByRef TotalFileCount As Integer)
    Dim FileName As String = Nothing
    Try
        For Each Directory In IO.Directory.GetDirectories(DirectoryPath)
            Search2(Directory, TotalFileCount)
        Next
        For Each File In IO.Directory.GetFiles(DirectoryPath, "*")
            FileName = New IO.FileInfo(File).FullName
            TotalFileCount += 1
        Next
    Catch ua As UnauthorizedAccessException
        ListBox1.Items.Add("Exception: " & ua.Message & " " & FileName)
    Catch ex As Exception
        ListBox1.Items.Add("Exception: " & ex.Message & " " & FileName)
    End Try
End Sub

In addition It would be easy to understand, I think, if you just return the number of files (use function instead of sub and a ByRef parameter) and sum this value to get the total number.

Here is a method to try

Public Function FileCount(DirPath As String, Optional IncludeSubDirs As Boolean = True) As Long
    Dim rv As Long = 0L
    Try
        If IncludeSubDirs Then
            For Each dirname As String In IO.Directory.GetDirectories(DirPath)
                rv += FileCount(dirname, IncludeSubDirs)
            Next
            rv += IO.Directory.GetFiles(DirPath).Length
        End If
    Catch ua As UnauthorizedAccessException
        'Stop
    Catch ex As Exception
        'Stop
    End Try
    Return rv
End Function

Tested with

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim DirectoryPath As String = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
    Dim stpw As Stopwatch = Stopwatch.StartNew

    Dim TotalFileCount As Long = FileCount(DirectoryPath)

    stpw.Stop()
    Dim rslts As String = String.Format("Total Files = {0:n0}.  Took {1:n0} ms.", TotalFileCount, stpw.ElapsedMilliseconds)
    Debug.WriteLine(rslts)
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM