Surf Directory - C# Programming Exercise

In this exercise, you need to create a program that displays the files and folders in the current folder and allows the user to move up and down the list. If the user presses Enter on a folder name, they will enter that folder. If they press Enter on a file, the file will be opened. This exercise will help you work with file and folder navigation, directory manipulation, and file opening from a console application, all while handling user input and key events such as the Enter key.

 Category

Additional Libraries

 Exercise

Surf Directory

 Objective

Create a program that displays the files in the current folder and allows the user to move up and down the list. If the user presses Enter on a folder name, they will enter that folder. If they press Enter on a file, the file will be opened.

 Write Your C# Exercise

// Import necessary namespaces
using System;
using System.IO;
using System.Linq;

class SurfDirectory
{
    // Main method where the program execution starts
    static void Main()
    {
        string currentPath = Directory.GetCurrentDirectory(); // Start in the current directory
        NavigateDirectory(currentPath); // Call the method to start navigating
    }

    // Method to navigate through the directory
    static void NavigateDirectory(string path)
    {
        while (true)
        {
            // Get all directories and files in the current path
            var directories = Directory.GetDirectories(path);
            var files = Directory.GetFiles(path);

            // Display the list of directories and files
            Console.Clear();
            Console.WriteLine($"Current Directory: {path}");
            Console.WriteLine("Directories:");
            foreach (var directory in directories)
            {
                Console.WriteLine($"[DIR] {Path.GetFileName(directory)}");
            }

            Console.WriteLine("\nFiles:");
            foreach (var file in files)
            {
                Console.WriteLine($"[FILE] {Path.GetFileName(file)}");
            }

            // Ask for user input
            Console.WriteLine("\nEnter the name of the folder or file to open, or '..' to go up a level.");
            Console.Write("Your choice: ");
            string choice = Console.ReadLine();

            // Handle navigation
            if (choice == "..") // Go up to the parent directory
            {
                string parentDir = Directory.GetParent(path).FullName;
                if (Directory.Exists(parentDir))
                {
                    path = parentDir; // Change to parent directory
                }
            }
            else
            {
                // Check if the choice is a directory
                var selectedDirectory = directories.FirstOrDefault(d => Path.GetFileName(d) == choice);
                if (selectedDirectory != null)
                {
                    path = selectedDirectory; // Change to the selected directory
                }
                else
                {
                    // Check if the choice is a file
                    var selectedFile = files.FirstOrDefault(f => Path.GetFileName(f) == choice);
                    if (selectedFile != null)
                    {
                        // Open the file (just display the file contents here)
                        Console.Clear();
                        Console.WriteLine($"Opening file: {selectedFile}");
                        Console.WriteLine("\nFile contents:");
                        try
                        {
                            string fileContents = File.ReadAllText(selectedFile);
                            Console.WriteLine(fileContents);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"Error reading file: {ex.Message}");
                        }

                        // Wait for user input before going back to the directory
                        Console.WriteLine("\nPress any key to go back to the directory...");
                        Console.ReadKey();
                    }
                    else
                    {
                        Console.WriteLine("Invalid choice, please try again.");
                    }
                }
            }
        }
    }
}

 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#.

  •  Subdirectories

    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 sear...

  •  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 "...