C# DirectoryInfo GetFiles(String)

Description

DirectoryInfo GetFiles(String) Returns a file list from the current directory matching the given search pattern.

Syntax

DirectoryInfo.GetFiles(String) has the following syntax.


public FileInfo[] GetFiles(
  string searchPattern
)

Parameters

DirectoryInfo.GetFiles(String) has the following parameters.

  • searchPattern - The search string, such as "*.txt".

Returns

DirectoryInfo.GetFiles(String) method returns

Example

Returns a file list from the current directory matching the given search pattern.


using System;//from  ww w.j  a v a2  s  .  com
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        DirectoryInfo di = new DirectoryInfo(@"C:\Users\");
        foreach (var fi in di.GetFiles())
        {
            Console.WriteLine(fi.Name);
        }
        Console.WriteLine("Search pattern *2* returns:");
        foreach (var fi in di.GetFiles("*2*"))
        {
            Console.WriteLine(fi.Name);
        }
        Console.WriteLine("Search pattern test?.txt returns:");
        foreach (var fi in di.GetFiles("test?.txt"))
        {
            Console.WriteLine(fi.Name);
        }
        Console.WriteLine("Search pattern AllDirectories returns:");
        foreach (var fi in di.GetFiles("*", SearchOption.AllDirectories))
        {
            Console.WriteLine(fi.Name);
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.IO »




BinaryReader
BinaryWriter
Directory
DirectoryInfo
DriveInfo
File
FileInfo
FileStream
MemoryStream
Path
StreamReader
StreamWriter
StringReader
StringWriter