ArrayList - Text file reader C# Exercise - C# Programming Course

 Exercise

ArrayList - Text file reader

 Objetive

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

 Example Code

// 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
    }
}

More C# Exercises of Dynamic Memory Management

 Implementing a queue using array
Implementing a queue...
 Implementing a stack using array
Implementing a stack...
 Queue Collections
Create a string queue using the Queue class that already exists in the DotNet platform....
 Queue Stack Reverse Polish Notation
Create a program that reads a Reverse Polish Notation expression from a text file, for example: 3 4 6 5 - + * 6 + (Result 21) Each item will be...
 ArrayList
Create a string list using the ArrayList class that already exists in the .NET platform. Once created, display all the items stored in the list. In...
 ArrayList duplicate a text file
Create a program that reads from a text file and stores it to another text file by reversing the order of lines. For example, an input text file li...
 Unlimited sum
Create a program to allow the user to enter an unlimited amount of numbers. Also, they can enter the following commands: "sum", to display the sum of...
 Hast Table - Dictionary
Submit your dictionary here using a hash table....
 Parenthesis
Implement a function to check if a sequence of open and closed parentheses is balanced. In other words, check if each open parenthesis corresponds to ...
 Mix and sort files
Create a program that reads the contents of two different files, merges them, and sorts them alphabetically. For example, if the files contain: "Dog C...
 ArrayList of Points
Create a structure named "Point3D" to represent a point in 3D space with coordinates X, Y, and Z. Create a program that has a menu where the user c...
 Search in file
Create a program that reads a text file, saves its content to an ArrayList, and asks the user to enter sentences to search within the file. The pro...

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