Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

C# Program to Search Directories and List Files

  • Last Updated : 01 Nov, 2021

Given files and directories, now our task is to search these files and directories using C#. So to do this task we use the following methods:

1. SearchOption: This method is used to specify whether to search the current directory or the current directory with all subdirectories.


public enum SearchOption

It will take two fields that is AllDirectories and TopDirectoryOnly. AllDirectories field is used to perform the search that contains the current directory and all its subdirectories in a search operation. And TopDirectoryOnly field is used to search only in the main directory.

2. GetFiles: This method is used to return the name of the files present in a particular directory or subdirectory. Or we can say that it returns the name along with the path of the files that are available in the given directory. 


public static string[] GetFiles (string path);

Where the path is the directory to search. This string is not case-sensitive. Here the path can be the relative or absolute path.


1. Read the directory and search in C drive A folder using searchoption AllDirectories keyword

list = Directory.GetFiles("C:\\A\\","*.*", SearchOption.AllDirectories)

2. Iterate through the list and display using foreach loop

foreach (string file in list)


In this example, we are displaying the list of file names along with their path by searching in the C drive – A directory.


// C# program to search directories and list files 
using System;
using System.IO;
class GFG{
static void Main()
    // Here we search the file present in C drive
    // and A directory. Using SearchOption 
    string[] list = Directory.GetFiles("C:\\A\\", "*.*"
    // Display the file names 
    // Present in the A directory 
    foreach (string file in list)



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!