Subdirectories - C# Programming Exercise

In this exercise, you need to create a program that stores the files located in a specific folder and its subfolders. Then, the program should ask the user for a search text and display the files whose names contain that text. The program will end when the user enters an empty search string. This exercise will help you work with file manipulation, directory exploration, file name searching, and user input handling in a console application.

 Category

Additional Libraries

 Exercise

Subdirectories

 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

// 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;
    }
}

 Share this C# exercise

 More C# Programming Exercises of Additional Libraries

Explore our set of C# programming 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#.

  •  Date and time

    In this exercise, you need to create a program that displays the current date and time in the following format:"Today is 6 of February of 2015. It´s 03:23:12".

  •  Display directory

    In this exercise, you need to create a program that shows all the files in the current folder. The program should list the files available in the directory where the program...

  •  Display executable files in directory

    In this exercise, you need to create a program that shows the names of all executable files (.com, .exe, .bat, .cmd) in the current folder, excluding the full path. The prog...

  •  Date and time continuous

    In this exercise, you need to create a program that displays the current time in the top-right corner of the screen with the format "HH:mm:ss". The program should pause for ...

  •  Sitemap creator

    In this exercise, you need to create a program that displays the contents of a preliminary "sitemap" on the screen. The sitemap should be generated from the list of "...

  •  List of images as HTML

    In this exercise, you need to create a program that generates an HTML file listing all the images (PNG and JPG files) in the current folder. The program...