C# DirectoryInfo GetFiles(String, SearchOption)

Description

DirectoryInfo GetFiles(String, SearchOption) Returns a file list from the current directory matching the given search pattern and using a value to determine whether to search subdirectories.

Syntax

DirectoryInfo.GetFiles(String, SearchOption) has the following syntax.


public FileInfo[] GetFiles(
  string searchPattern,
  SearchOption searchOption
)

Parameters

DirectoryInfo.GetFiles(String, SearchOption) has the following parameters.

  • searchPattern - The search string. For example, "System*" can be used to search for all directories that begin with the word "System".
  • searchOption - One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories.

Returns

DirectoryInfo.GetFiles(String, SearchOption) method returns

Example

Returns a file list from the current directory matching the given search pattern and using a value to determine whether to search subdirectories.


/*from   w ww. j  av  a 2 s . c o  m*/

using System;
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