Directory.GetFiles Method

   
Directory.GetFiles Method

Class

System.IO.Directory

Syntax

 Directory.GetFiles(   path   [,   searchpattern   ]) 
path (required; String)

A valid path to a directory

searchpattern (optional; String)

A file specification, including the wildcard characters * and ?

Return Value

An array of strings, each element of which contains the name of a file

Description

Returns the names of the files in a specified directory

Rules at a Glance

  • path can be either an absolute path (a complete path from the root directory to the directory whose filenames are to be retrieved) or a relative path (starting from the current directory to the directory whose filenames are to be retrieved).

  • 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.

  • If searchpattern is specified, the method returns only those files whose names 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 extension .txt:

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

Programming Tips and Gotchas

Since GetFiles can return an empty array, you can prevent an array-access error in either of two ways: you can iterate the returned array using the For Each... Next construct, or you can retrieve the value of the UBound function, which is -1 in the case of an uninitialized array.

See Also

Directory.GetDirectories Method, Directory.GetFileSystemEntries Method

   


VB.Net Language in a Nutshell
VB.NET Language in a Nutshell
ISBN: B00006L54Q
EAN: N/A
Year: 2002
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net