Invert a text file Learn programming Visual Basic (VB.net)

Lesson:

File Management


Exercise:

Invert a text file 17


Objetive:

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.


Code:

Imports System
Imports System.IO
Namespace InvertText
    Class Program
        Private Shared Sub Main(ByVal args As String())
            Console.Write("Enter name file: ")
            Dim fileName As String = Console.ReadLine()

            If File.Exists(fileName) Then
                Dim myfileRd As StreamReader = File.OpenText(fileName)
                Dim line As String
                Dim countLines As Integer = 0

                Do
                    line = myfileRd.ReadLine()
                    If line IsNot Nothing Then countLines += 1
                Loop While line IsNot Nothing

                myfileRd.Close()
                Dim lines As String() = New String(countLines - 1) {}
                Dim countLine As Integer = 0
                myfileRd = File.OpenText(fileName)
                line = ""

                Do
                    line = myfileRd.ReadLine()

                    If line IsNot Nothing Then
                        lines(countLine) = line
                        countLine += 1
                    End If
                Loop While line IsNot Nothing

                myfileRd.Close()
                Dim myfileWr As StreamWriter = File.CreateText(fileName & ".tnv")

                For i As Integer = lines.Length - 1 To 0 + 1
                    myfileWr.WriteLine(lines(i))
                Next

                myfileWr.Close()
            Else
                Console.WriteLine("The file no exists.")
            End If
        End Sub
    End Class
End Namespace