Group
Using Additional Libraries in C#
Objective
1. Use the Directory.GetFiles() method to retrieve the files from the specified folder and its subfolders.
2. Store the names of all the files.
3. Ask the user to input a search string.
4. Display all the files that contain the search string in their name.
5. Repeat the process until the user enters an empty string to stop the program.
6. Make sure to handle exceptions like invalid paths or inaccessible directories.
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 C# Exercise
Show C# Code
using System;
using System.IO;
using System.Linq;
class Program
{
static void Main()
{
Console.Write("Enter the path of the folder: ");
string folderPath = Console.ReadLine();
if (!Directory.Exists(folderPath))
{
Console.WriteLine("The specified folder does not exist.");
return;
}
var files = GetFilesFromDirectory(folderPath);
while (true)
{
Console.Write("Enter text to search in file names (or press Enter to exit): ");
string searchText = Console.ReadLine();
if (string.IsNullOrEmpty(searchText))
{
Console.WriteLine("Exiting program.");
break;
}
var matchingFiles = files.Where(file => file.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0).ToList();
if (matchingFiles.Any())
{
Console.WriteLine("Matching files:");
foreach (var file in matchingFiles)
{
Console.WriteLine(file);
}
}
else
{
Console.WriteLine("No files found with that search text.");
}
}
}
static string[] GetFilesFromDirectory(string directoryPath)
{
string[] files = Directory.GetFiles(directoryPath, "*", SearchOption.AllDirectories);
return files;
}
}
Output
Enter the path of the folder: C:\Users\Example\Documents
Enter text to search in file names (or press Enter to exit): report
Matching files:
C:\Users\Example\Documents\Report_2023.txt
C:\Users\Example\Documents\AnnualReport_2023.txt
Enter text to search in file names (or press Enter to exit): summary
Matching files:
C:\Users\Example\Documents\Summary_2023.txt
Enter text to search in file names (or press Enter to exit):
Exiting program.