How to: Determine How Many Files Are in a Directory in Visual Basic

You can use the My.Computer.FileSystem.GetFiles Method to return a read-only collection of strings representing the names of files within the specified directory. Then you can use the Count property to determine the number of files.

To determine the number of files in a directory

  1. Use the GetFiles method to return the collection of files in the specified directory. This example returns the files in the directory named TestDir.

    Dim counter As _
    System.Collections.ObjectModel.ReadOnlyCollection(Of String)
    counter = My.Computer.FileSystem.GetFiles("C:\TestDir")
    
  2. Use the Count property to determine the number of files in the collection. This example displays the result in a message box.

    MsgBox("number of files is " & CStr(counter.Count))
    

Example

This example, which presents the above snippet in complete form, counts the number of files in TestDir and reports it in a message box.

Dim counter As _
System.Collections.ObjectModel.ReadOnlyCollection(Of String)
counter = My.Computer.FileSystem.GetFiles("C:\TestDir")
MsgBox("number of files is " & CStr(counter.Count))

Compiling the Code

This example requires:

  • Access to the members of the System.Collections namespace. Add an Imports statement if you are not fully qualifying member names in your code. For more information, see Imports Statement (.NET Namespace and Type).

  • A directory named TestDir at the specified location. Replace the path with the path of the directory you wish to examine.

Robust Programming

The following conditions may cause an exception:

See Also

Tasks

How to: Get the Collection of Files in a Directory in Visual Basic

How to: Find Files with a Specific Pattern in Visual Basic

Reference

My.Computer.FileSystem.GetFiles Method

Other Resources

File, Directory, and Drive Properties in Visual Basic