Programming Course in C# ¡Free!

Subdirectories

 Saturday, April 06, 2013 published by Exercises C#
Proposed exercise

Create a program to store the files which are in a certain directory and its subdirectories. 

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.


Solution

using System;
using System.IO;

class Subdirectories
{
    static void Main()
    {
        try
        {
            string text = "";

            Console.Write("Enter a directory for search: ");
            text = Console.ReadLine();

            while (text != "")
            {
                DirectoryInfo directory = new DirectoryInfo(text);

                // Save files and directories
                FileInfo[] files = directory.GetFiles("*.*");
                DirectoryInfo[] directories = directory.GetDirectories();

                // Write the files
                int i = 0;
                for (; i < files.Length; i++)
                    Console.WriteLine(((FileInfo)files[i]).FullName);

                // Write the directories
                for (i = 0; i < directories.Length; i++)
                    Console.WriteLine(((DirectoryInfo)directories[i]).FullName);


                Console.Write("\nEnter a directory for search: ");
                text = Console.ReadLine();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}