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
C# Exercise Example
// 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.");
}
}
}
}
}
}