Exercise
Arraylist Duplicate A Text File
Objetive
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 like:
yesterday Real Madrid
won against
Barcelona FC
will be stored in an output text file like:
Barcelona FC
won against
yesterday Real Madrid
Example Code
using System;
using System.IO;
using System.Collections;
namespace TextFileInvert
{
class Program
{
static void Main(string[] args)
{
Console.Write("Introduce el nombre del fichero: ");
string nombreArchivo = Console.ReadLine();
if (!File.Exists(nombreArchivo))
{
Console.Write("El archivo no existe!");
return;
}
try
{
StreamReader miArchivo;
miArchivo = File.OpenText(nombreArchivo);
string line;
ArrayList miLista = new ArrayList();
do
{
line = miArchivo.ReadLine();
if (line != null)
miLista.Add(line);
}
while (line != null);
miArchivo.Close();
StreamWriter miArchivoAlReves = File.CreateText(
nombreArchivo + "-reverse.txt");
int tamanyoArchivo = miLista.Count;
for (int i = tamanyoArchivo - 1; i >= 0; i--)
{
miArchivoAlReves.WriteLine(miLista[i]);
}
miArchivoAlReves.Close();
}
catch (Exception e)
{
Console.WriteLine("Error, " + e.Message);
}
Console.ReadLine();
}
}
}