Exercise
Subdirectories
Objetive
Create a program to store the files that are located in a particular folder and its subfolders.
Then, it will ask the user which text to search and it will display the files containing that text in their name.
Program will end when the user enters an empty search string.
Example Code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Subdirectories
{
static void Main()
{
Console.WriteLine("Enter the directory path to scan:");
string directoryPath = Console.ReadLine();
if (!Directory.Exists(directoryPath))
{
Console.WriteLine("The directory does not exist. Please try again with a valid path.");
return;
}
List filesList = GetFilesInDirectoryAndSubdirectories(directoryPath);
while (true)
{
Console.WriteLine("\nEnter the text to search in file names (leave empty to exit):");
string searchText = Console.ReadLine();
if (string.IsNullOrWhiteSpace(searchText))
{
Console.WriteLine("Exiting the program.");
break;
}
var matchedFiles = filesList.Where(f => f.Contains(searchText, StringComparison.OrdinalIgnoreCase)).ToList();
if (matchedFiles.Any())
{
Console.WriteLine("\nFiles containing the search text:");
foreach (var file in matchedFiles)
{
Console.WriteLine(file);
}
}
else
{
Console.WriteLine("\nNo files found containing the search text.");
}
}
}
static List GetFilesInDirectoryAndSubdirectories(string path)
{
List files = new List();
files.AddRange(Directory.GetFiles(path));
var subdirectories = Directory.GetDirectories(path);
foreach (var subdir in subdirectories)
{
files.AddRange(GetFilesInDirectoryAndSubdirectories(subdir));
}
return files;
}
}