Arraylist - Text File Reader - C# Programming Exercise

In this exercise, you need to create a basic text file reader that displays 21 lines of text and allows the user to navigate using the up and down arrow keys, and exit using the ESC key.

The program should have three main methods:
1. ReadFile: This method reads the text file and stores it in memory.
2. ShowMenu: Clears the console, sets the top and bottom lines of the console (row 23), changes colors using Console.BackgroundColor, Console.ForegroundColor, ConsoleColor, and Console.SetCursorPosition(column, row). Once the menu is prepared, place the cursor in the second row.
3. ShowFrom: This method writes 21 lines, considering the position of the first line to display.

The main program flow should be as follows: ShowMenu, ShowFrom, ReadKey, ShowMenu, ShowFrom, ReadKey, and so on. The program should allow the user to navigate through the lines of the file using the arrow keys, and it should terminate when the user presses the ESC key.

This exercise is ideal for practicing file handling, keyboard input, and console manipulation in C#, improving user experience in interactive navigation.

 Category

Dynamic Memory Management

 Exercise

Arraylist - Text File Reader

 Objective

provide your basic text file reader here, which displays 21 lines of text and allows the user to navigate using the up and down arrow keys, and exit using the ESC key.

Hints:
The text file reader should have three methods:

ReadFile (reads the text file and stores it in memory)
ShowMenu (clears the console, sets the top and bottom lines of the console [row 23], changes colors using Console.BackgroundColor, Console.ForegroundColor, ConsoleColor and Console.SetCursorPosition(column, row). Once the menu is prepared, remember to set the cursor in the second row).
ShowFrom (writes 21 lines, considering the position of the first line to write)
The main program logic should be as follows: ShowMenu, ShowFrom, ReadKey, ShowMenu, ShowFrom, ReadKey....

 Write Your C# Exercise

// Importing necessary namespaces for file handling and console manipulation
using System;  // For basic input/output and handling console operations
using System.Collections;  // To use ArrayList for dynamic list handling
using System.IO;  // For file input/output operations

class Program
{
    // The list to store the lines from the text file
    static ArrayList lines = new ArrayList();  // ArrayList to hold all the lines from the text file
    // The current position (index of the first line to be shown)
    static int currentLineIndex = 0;  // Keeps track of the current position in the file

    // Method to read the file and store its lines in the 'lines' ArrayList
    static void ReadFile(string filePath)
    {
        // Try to open and read the file
        try
        {
            // Read all lines from the text file and store them in the ArrayList
            string[] fileLines = File.ReadAllLines(filePath);
            lines.AddRange(fileLines);  // Add all lines to the 'lines' ArrayList
        }
        catch (Exception ex)
        {
            // Display error if the file cannot be read
            Console.WriteLine("Error reading file: " + ex.Message);  // Show error message if file can't be read
        }
    }

    // Method to show the menu and set up the display
    static void ShowMenu()
    {
        // Clear the console screen
        Console.Clear();  // Clears the console screen for refreshing the display
        
        // Set up background and foreground colors for the menu
        Console.BackgroundColor = ConsoleColor.Black;  // Set background color to black
        Console.ForegroundColor = ConsoleColor.White;  // Set text color to white

        // Set the cursor to the top row (row 1)
        Console.SetCursorPosition(0, 0);  // Move cursor to the top-left corner of the console
        
        // Display a simple header
        Console.WriteLine("Text File Reader - Use UP/DOWN arrows to navigate, ESC to exit.");  // Display instructions at the top
    }

    // Method to show the 21 lines starting from the current index
    static void ShowFrom(int startLineIndex)
    {
        // Ensure we don't go beyond the file's end
        int endLineIndex = Math.Min(startLineIndex + 21, lines.Count);  // Calculate the end line index based on current position

        // Display lines from the 'lines' array starting from 'startLineIndex'
        for (int i = startLineIndex; i < endLineIndex; i++)
        {
            // Adjust cursor position to display lines one by one starting from row 2 (skip the header)
            Console.SetCursorPosition(0, i - startLineIndex + 2);  // Set the cursor position dynamically for each line
            Console.WriteLine(lines[i]);  // Display the current line
        }
    }

    // Main method to execute the program logic
    static void Main(string[] args)
    {
        // Ask the user for the file path
        Console.Write("Enter the file path: ");  // Prompt the user for the file path
        string filePath = Console.ReadLine();  // Read the user input as the file path

        // Read the file contents
        ReadFile(filePath);  // Call ReadFile method to load the file into memory

        // Main program loop to handle navigation and display
        while (true)
        {
            // Show the menu and the lines from the current position
            ShowMenu();  // Call ShowMenu to display the navigation instructions
            ShowFrom(currentLineIndex);  // Call ShowFrom to display the lines starting from currentLineIndex

            // Get user input for navigation
            var key = Console.ReadKey(true).Key;  // Read key input without echoing to console

            // If the ESC key is pressed, break out of the loop and exit
            if (key == ConsoleKey.Escape)
            {
                break;  // Exit the program if ESC is pressed
            }
            // If the DOWN arrow key is pressed, move to the next 21 lines (if possible)
            else if (key == ConsoleKey.DownArrow)
            {
                if (currentLineIndex + 21 < lines.Count)  // Check if there are more lines to show
                {
                    currentLineIndex += 21;  // Move the index forward by 21 lines
                }
            }
            // If the UP arrow key is pressed, move to the previous 21 lines (if possible)
            else if (key == ConsoleKey.UpArrow)
            {
                if (currentLineIndex - 21 >= 0)  // Ensure we don't move past the beginning of the file
                {
                    currentLineIndex -= 21;  // Move the index backward by 21 lines
                }
            }
        }

        // Exiting the program
        Console.WriteLine("\nProgram terminated.");  // Inform the user that the program has ended
    }
}

 Share this C# exercise

 More C# Programming Exercises of Dynamic Memory Management

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

  •  Hast Table - Dictionary

    In this exercise, you need to create a dictionary using a hash table. The purpose of this exercise is to practice the implementation of an efficient data struc...

  •  Parenthesis

    In this exercise, you need to implement a function to check if a sequence of open and closed parentheses is balanced. In other words, the function should check if every open...

  •  Mix and sort files

    In this exercise, you need to create a program that reads the contents of two different files, merges them, and sorts them alphabetically. The program should be able to take...

  •  ArrayList of Points

    In this exercise, you need to create a structure named "Point3D" to represent a point in 3D space with X, Y, and Z coordinates. The structure should allow storing and manipu...

  •  Search in file

    In this exercise, you need to create a program that reads the contents of a text file, saves the content into an ArrayList, and prompts the user to enter sentences to...

  •  Implementing a queue using array

    In this exercise, you need to implement a queue in C#. A queue is a data structure that follows the FIFO (First In, First Out) principle, meaning the first ele...