Search Files by Name in Folder and Subfolders in C#

In this exercise, you will create a program that stores the names of files located in a specific folder and its subfolders. The program will then prompt the user to enter a search text. It will display all the files that contain that search text in their names. The program will continue to ask for new search terms until the user enters an empty string, at which point it will terminate.

This program will help you practice file and directory traversal, searching for substrings within file names, and handling user input dynamically. You will use recursion to search through all the subfolders of the given folder.



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

 Copy C# Code
using System;  // For general system functions
using System.IO;  // For file and directory handling
using System.Linq;  // For LINQ to handle search operations

class Program
{
    static void Main()
    {
        // Ask the user to enter the folder path
        Console.Write("Enter the path of the folder: ");
        string folderPath = Console.ReadLine();

        // Validate the folder path
        if (!Directory.Exists(folderPath))
        {
            Console.WriteLine("The specified folder does not exist.");
            return;
        }

        // Get all files in the specified folder and its subfolders
        var files = GetFilesFromDirectory(folderPath);

        // Repeat the search process until the user enters an empty string
        while (true)
        {
            // Ask the user for the search term
            Console.Write("Enter text to search in file names (or press Enter to exit): ");
            string searchText = Console.ReadLine();

            // If the search text is empty, exit the program
            if (string.IsNullOrEmpty(searchText))
            {
                Console.WriteLine("Exiting program.");
                break;
            }

            // Find and display files that contain the search text in their name
            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);  // Display the file names
                }
            }
            else
            {
                Console.WriteLine("No files found with that search text.");
            }
        }
    }

    // Method to retrieve all files from the directory and its subdirectories
    static string[] GetFilesFromDirectory(string directoryPath)
    {
        // Get all files in the directory and its subdirectories recursively
        string[] files = Directory.GetFiles(directoryPath, "*", SearchOption.AllDirectories);

        return files;  // Return the list of 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.

Share this C# Exercise

More C# Practice Exercises of Using Additional Libraries in C#

Explore our set of C# Practice Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  • Display Current Date and Time in C#

    In this exercise, you will create a program that displays the current date and time in a specific format. The format should be as follows: "Today is 6 of February of 2015. It's 03:...

  • Display Files in the Current Folder in C#

    In this exercise, you will create a C# program that retrieves and displays all files in the current folder. You will use the System.IO namespace, particularly the Directory.GetFile...

  • Display Executable Files in Current Folder in C#

    In this exercise, you will create a C# program that retrieves and displays the names of all executable files in the current folder. The program will search for files with specific ...

  • Display Current Time in Top-Right Corner in C#

    In this exercise, you will create a C# program that displays the current time in the top-right corner of the console screen. The program will update the time every second, showing ...

  • Generate a Sitemap from HTML Files in C#

    In this exercise, you will create a C# program that generates a preliminary "sitemap" file from the list of .html files in the current folder. The program will display the sitemap ...

  • Generate HTML File Listing Images in the Current Folder in C#

    In this exercise, you will create a C# program that generates an HTML file listing all images (PNG and JPG) in the current folder. The program will scan the current directory, iden...