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.
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.
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.
- 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”