counting the number of files in a folder

harish13's Avatar
Go4Expert Member
i want to count the number of files present in a folder how can i do this
thank u in advance
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
See my reply to your other thread at
ocena's Avatar, Join Date: Aug 2006
Light Poster
if you are using vb 2005 then here it is
Code: VB
Dim SearchCriteria As String = String.Empty  ' Globals
Dim FileFound As Integer

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
            FileFound = 0 ' reset counter
            MessageBox.Show("Number of files matching : " + GetFileCount(TextBox2.Text).ToString())
        Catch ex As Exception
            MessageBox.Show("Error occured: " + ex.Message)
        End Try
End Sub

Private Function GetFileCount(ByVal path As String) As Integer
        Dim CriteriaPath, files, dirs As String

        CriteriaPath = path.Substring(0, path.LastIndexOf("\"))

        If SearchCriteria.Length = 0 Then
            SearchCriteria = "*.*"
            SearchCriteria = path.Substring(path.LastIndexOf("\") + 1)
        End If

        For Each files In Directory.GetFiles(CriteriaPath, SearchCriteria)
            FileFound += 1

        For Each dirs In Directory.GetDirectories(CriteriaPath)
            GetFileCount(dirs + "\" + SearchCriteria) ' recursive call

        Return FileFound
End Function

Last edited by shabbir; 7Aug2006 at 12:19.. Reason: Code formating.