Subdirectories Learn programming C#

Lesson:

Additional Libraries


Exercise:

Subdirectories


Objetive:

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.


Code:

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());
        }
    }
}

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.