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

 

Updated: July 20, 2015

For the latest documentation on Visual Studio 2017, see Visual Studio 2017 Documentation.

The overloads of the FileSystem.GetFiles method return a read-only collection of strings representing the names of the files within a directory:

An empty collection is returned if no files matching the specified pattern are found.

To list files in a directory

  • Use one of the FileSystem.GetFiles method overloads, supplying the name and path of the directory to search in the directory parameter. The following example returns all files in the directory and adds them to ListBox1.

            For Each foundFile As String In My.Computer.FileSystem.GetFiles(
              My.Computer.FileSystem.SpecialDirectories.MyDocuments)
    
                listBox1.Items.Add(foundFile)
            Next
    

The following conditions may cause an exception:

GetFiles
How to: Find Files with a Specific Pattern
How to: Find Subdirectories with a Specific Pattern

Show: