VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/c-sharp-program-to-search-sub-directory-in-a-given-directory/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 24 Mar, 2022

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: 

  • AllDirectories: This is used to perform the search that contains the current directory and all its subdirectories in a search operation. 
  • TopDirectoryOnly: This is used to search only in the main directory.
     

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:

  • Using SearchOption we will find all the files in a subdirectory.
  • Then using GetFiles, we will extract all those files that are present in the directory and initialize them to a string array.
  • Now simple traverse that string array using for each loop.
  • Using conditional operator we will match whether file names are equal or not. Return "yes" if the file is found else "no"

Example 1:

Output:

no

Example 2:

Output:

yes
Comment

Explore