Ejercicio
Arraylist - Lector De Archivos De Texto
Objectivo
Entregue aquí su lector básico de archivos de texto.
Este lector de archivos de texto siempre muestra 21 líneas del archivo de texto, y el usuario podría usar la tecla up para mostrar la línea anterior, la tecla down para mostrar la siguiente línea y la tecla ESC para salir.
Sugerencias:
El lector de archivos de texto debe tener 3 métodos:
- ReadFile (Leer el archivo de texto y almacenarlo en la memoria)
- ShowMenu (Borrar la consola y preparar la línea superior y la línea inferior [raw 23] de la consola, cambiando los colores usando Console.BackgroundColor, Console.ForegroundColor, ConsoleColor y Console.SetCursorPosition(column, raw). Una vez preparado el menú, recuerda colocar el cursor en el segundo raw).
- ShowFrom (escribir 21 líneas, considerando la posición de la primera línea a escribir)
La lógica del programa principal debe ser como: ShowMenu, ShowFrom, ReadKey, ShowMenu, ShowFrom, ReadKey....
Ejemplo Ejercicio C#
Mostrar Código C#
// 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
}
}
Salida
Enter the file path: sample.txt
Text File Reader - Use UP/DOWN arrows to navigate, ESC to exit.
Line 1 of the file
Line 2 of the file
...
Line 21 of the file
User Navigates:
Press DOWN Arrow to show lines 22-42, UP Arrow to go back to lines 1-21.
Press ESC to exit the program.
Exit:
Program terminated.
Código de Ejemplo Copiado!
Comparte este Ejercicio C# Sharp