string path = @"C:\Users\Example\Documents"; string searchPattern = "*.txt"; string[] files = Directory.GetFiles(path, searchPattern,SearchOption.AllDirectories); foreach (string file in files) { Console.WriteLine(file); }
string path = @"C:\Users\Example\Desktop"; string searchPattern = "*.png"; string[] files = Directory.GetFiles(path, searchPattern, SearchOption.TopDirectoryOnly); foreach (string file in files) { Console.WriteLine(file); }Description: SearchOption is used to specify the search option in the GetFiles method of the Directory class. The enumeration has two values: AllDirectories and TopDirectoryOnly. In the example, the first example shows how to search for all files in a directory including all subdirectories, while the second example shows how to search for files only in the directory and not in subdirectories. Package library: The package library used in the examples above is System.IO.Directory. This is a built-in package available in C# to manipulate directories and files in the file system.