Objective
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.
Write Your C# Exercise
C# Exercise Example
// Importing necessary namespaces
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Subdirectories
{
// Main method where the program execution starts
static void Main()
{
Console.WriteLine("Enter the directory path to scan:");
string directoryPath = Console.ReadLine(); // Ask the user for the directory path
if (!Directory.Exists(directoryPath))
{
Console.WriteLine("The directory does not exist. Please try again with a valid path.");
return;
}
// Store files and subdirectories
List filesList = GetFilesInDirectoryAndSubdirectories(directoryPath);
// Loop for searching files by name
while (true)
{
Console.WriteLine("\nEnter the text to search in file names (leave empty to exit):");
string searchText = Console.ReadLine(); // Get the search text from user
if (string.IsNullOrWhiteSpace(searchText))
{
Console.WriteLine("Exiting the program.");
break; // Exit the program if the search string is empty
}
// Search for files that contain the search text in their names
var matchedFiles = filesList.Where(f => f.Contains(searchText, StringComparison.OrdinalIgnoreCase)).ToList();
// Display the matching files
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.");
}
}
}
// Method to get all files from a directory and its subdirectories
static List GetFilesInDirectoryAndSubdirectories(string path)
{
List files = new List();
// Get all files in the current directory
files.AddRange(Directory.GetFiles(path));
// Get all subdirectories in the current directory
var subdirectories = Directory.GetDirectories(path);
// Recursively get files from subdirectories
foreach (var subdir in subdirectories)
{
files.AddRange(GetFilesInDirectoryAndSubdirectories(subdir));
}
return files;
}
}