Export (0) Print
Expand All
Expand Minimize

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

You can use the 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 = 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))
    
    
    

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 = My.Computer.FileSystem.GetFiles("C:\TestDir")
MsgBox("number of files is " & CStr(counter.Count))


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.

The following conditions may cause an exception:

Community Additions

ADD
Show:
© 2015 Microsoft