Visual Basic 2005 in a Nutshell (In a Nutshell (OReilly))

Directory.GetFiles Method

Class

System.IO.Directory

Syntax

Dim result( ) As String = Directory.GetFiles (path[, _ searchPattern[, searchOption]])

path (required; String)

A valid path to a directory

searchPattern (optional; String)

A file specification, optionally including the wildcard characters * and ?

searchOption (optional; SearchOption enumeration)

New in 2005. One of the following Microsoft.VisualBasic.FileIO.SearchOption enumeration members:

Member

Description

AllDirectories

The method returns information about all nested subdirectories.

TopDirectoryOnly

The method returns information about the top-most directory only.

If omitted, TopDirectoryOnly is used.

Description

The GetFiles method returns an array of strings, with each string containing the name of one file from the specified main directory, optionally matching a pattern. The results can optionally include all nested subdirectories.

Usage at a Glance

  • path can be either an absolute path or a relative path from the current directory.

  • path can be either a path on the local system, the path of a mapped network drive, or a UNC path.

  • path cannot contain wildcard characters, but searchPattern can.

  • If searchPattern is specified, the method returns only those files with names that match the string, which can contain wildcard characters. Otherwise, the function returns the names of all the files in the path directory.

  • If the directory specified by path has no files, or if no files match searchPattern, an empty array is returned.

Example

The following code displays all files in c:\ that have the ".txt" extension:

Dim allTextFiles( ) As String Dim counter As Integer allTextFiles = Directory.GetFiles("c:\", "*.txt") For counter = 0 To UBound(allTextFiles) Console.WriteLine(allTextFiles(counter)) Next counter

Version Differences

  • The searchOption parameter is new with Visual Basic 2005.

  • Visual Basic 2005 includes a My.Computer.FileSystem.GetFiles method that provides similar functionality.

See Also

Directory.GetDirectories Method, Directory.GetFileSystemEntries Method

Категории