DirectoryInfo.GetFiles Method
Returns a file list from the current directory.
Namespace: System.IO
Assembly: mscorlib (in mscorlib.dll)
| Exception | Condition |
|---|---|
| DirectoryNotFoundException | The path is invalid, such as being on an unmapped drive. |
The EnumerateFiles and GetFiles methods differ as follows:
When you use EnumerateFiles, you can start enumerating the collection of FileInfo objects before the whole collection is returned.
When you use GetFiles, you must wait for the whole array of FileInfo objects to be returned before you can access the array.
Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.
If there are no files in the DirectoryInfo, this method returns an empty array.
The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required.
This method pre-populates the values of the following FileInfo properties:
The following example shows how to get a list of files from a directory by using different search options. The example assumes a directory that has files named log1.txt, log2.txt, test1.txt, test2.txt, test3.txt, and a subdirectory that has a file named SubFile.txt.
Imports System.IO Module Module1 Sub Main() Dim di As DirectoryInfo = New DirectoryInfo("C:\ExampleDir") Console.WriteLine("No search pattern returns:") For Each fi In di.GetFiles() Console.WriteLine(fi.Name) Next Console.WriteLine() Console.WriteLine("Search pattern *2* returns:") For Each fi In di.GetFiles("*2*") Console.WriteLine(fi.Name) Next Console.WriteLine() Console.WriteLine("Search pattern test?.txt returns:") For Each fi In di.GetFiles("test?.txt") Console.WriteLine(fi.Name) Next Console.WriteLine() Console.WriteLine("Search pattern AllDirectories returns:") For Each fi In di.GetFiles("*", SearchOption.AllDirectories) Console.WriteLine(fi.Name) Next End Sub End Module ' This code produces output similar to the following: ' No search pattern returns: ' log1.txt ' log2.txt ' test1.txt ' test2.txt ' test3.txt ' Search pattern *2* returns: ' log2.txt ' test2.txt ' Search pattern test?.txt returns: ' test1.txt ' test2.txt ' test3.txt ' Search pattern AllDirectories returns: ' log1.txt ' log2.txt ' test1.txt ' test2.txt ' test3.txt ' SubFile.txt ' Press any key to continue . . .
- FileIOPermission
for reading directories. Associated enumeration: FileIOPermissionAccess.Read
Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.