Open In App

C# Program to Search Sub-Directory in a Given Directory

C# is a general-purpose,  object-oriented programming language pronounced as “C Sharp”. It is a lot syntactically similar to Java and is easy for users who have knowledge of C, C++, or Java. In this article, we will learn How can we use C# to search the sub-Directory in a given Directory.  So for  this task, we use the following methods:

1. SearchOption: This method is used to tell the compiler whether to do our search in the current directory or the current directory with all subdirectories.



Syntax:

public enum SearchOption

It will take two fields: 



2. GetFiles: When we need to fetch the names of the files present in a directory or subdirectory then the GetFiles function is used. It returns a string array containing the names of the files.  

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:

Example 1:




// C# code for search a subdirectory
// C: -> GFG ->
// Here only 1 file i.e Test.txt
using System;
using System.IO;
  
class GFG {
  
    static void Main()
    {
  
        // Here we search the file present in C drive
        // and GFG directory. Using SearchOption
        string[] list = Directory.GetFiles("C:\\GFG\\", "*.*",
                                           SearchOption.AllDirectories);
  
        string value = "GFG.txt"; // File to be searched
        int flag = 0;
        // Search the file names
        // Present in the A directory
        foreach(string file in list)
        {
            if (file == value) {
                flag = 1;
                break;
            }
        }
        if (flag == 1) {
            Console.WriteLine("yes");
        }
        else {
            Console.WriteLine("no");
        }
    }
}

Output:

no

Example 2:




// C# code for search subdirectory C: -> GFG ->
using System;
using System.IO;
  
class GFG {
  
    static void Main()
    {
  
        // Here we search the file present in C drive
        // and GFG directory. Using SearchOption
        string[] list = Directory.GetFiles("C:\\GFG\\", "*.*",
                                           SearchOption.AllDirectories);
  
        string value = "Test.txt"; // File to be searched
        int flag = 0;
  
        // Search the file names
        // Present in the A directory
        foreach(string file in list)
        {
            if (file == value) {
                flag = 1;
                break;
            }
        }
        if (flag == 1) {
            Console.WriteLine("yes");
        }
        else {
            Console.WriteLine("no");
        }
    }
}

Output:

yes

Article Tags :