In above folder I am having taken 4 types of files (.txt, .jpeg, .xlsx, .docx). Now we will write code to read and filter all the text files. After filtering the files, we will display the name of the files. So, for this example, first we will create a console application using c#.net, and add he below code in it.
string folderPath = "D:\\DemoRepo\\Myfolder";
if (Path.Exists(folderPath))
{
DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
var fileList = directoryInfo.GetFiles().Where(m => m.Extension == ".txt");
Console.WriteLine("Total Text File Count: " + fileList.Count());
foreach (var file in fileList)
{
Console.WriteLine(file.FullName);
}
}
Here in above code i have taken the local folder path in a variable named as folderPath. Now we need to validate the path exists or not. If the given path exists on that case, we will get directoryy detail by creating object of DirectoryInfo by passing the path of the folder. DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
After getting the directory info we will declare a variable and use GetFiles() to get all the files available in the directory. all the file files available in the directory. After getting all the files we will use LINQ where clause to apply the filter for files. Where i have user where cause and in this validated get all the files or filter the files whose extension in .txt. This will get all the files available in the directory. Her we don't need to apply loop to validate and filter each file.
var fileList = directoryInfo.GetFiles().Where(m => m.Extension == ".txt");
After getting all the text file list we displayed the count of the file and with the help of foreach loop displayed the text files name. Now let's add a break point and check the output.