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:
// 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