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.

Syntax:

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. 

Syntax:

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.

Approach

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)
{
    Console.WriteLine(file);
}

Example: 

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

C#




// 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\\", "*.*"
                                       SearchOption.AllDirectories);
                                         
    // Display the file names 
    // Present in the A directory 
    foreach (string file in list)
    {
        Console.WriteLine(file);
    }
}
}

Output:

C:\A\file.txt

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!