Programming Course in C# ¡Free!

Invert a text file

 Saturday, April 06, 2013 published by Exercises C#
Proposed exercise

Create a program to "invert" the contents of a text file: create a file with the same name ending in ".tnv" and containing the same lines as the original file but in reverse order (the first line will be the last one, the second will be the penultimate, and so on, until the last line of the original file, which should appear in the first position of the resulting file).

Hint: the easiest way, using only the programming structures we know so far, is reading the source files two times: the first time to count the amount of lines in the file, and the second time to store them in an array.

Output



Solution


using System;
using System.IO;


class InvertText
{
static void Main()
{
Console.Write("Enter name file: ");
string name = Console.ReadLine();

if (File.Exists(name))
{
StreamReader file = File.OpenText(name);
string line;
int count=0;

do
{
line = file.ReadLine();
if (line != null)
count++;
}
while (line != null);
file.Close();

string[] lines = new string[count]; 
count = 0;
line = "";

file = File.OpenText(name);

do
{
line = file.ReadLine();
if (line != null) 
{
lines[count] = line;
count++;
}
}
while (line != null);
file.Close();

StreamWriter myfileWr = File.CreateText(name + ".dat");

for (int i = lines.Length - 1; i > 0; i--) 
myfileWr.WriteLine( lines[i] );

myfileWr.Close();
}
else
Console.WriteLine("Error");
}
}