Text replacer Learn programming Visual Basic (VB.net)

Lesson:

File Management


Exercise:

Text replacer


Objetive:

Create a program to replace words in a text file, saving the result into a new file.

The file, the word to search and word to replace it with must be given as parameters:

replace file.txt hello goodbye

The new file would be named "file.txt.out" and contain all the appearances of "hello" replaced by "goodbye".


Code:

Imports System
Imports System.IO
Namespace Replace
    Class Program
        Private Shared Sub Main(ByVal args As String())
            ReplaceTextFile("file.txt", "Hola", "hola")
        End Sub

        Public Shared Sub ReplaceTextFile(ByVal urlFile As String, ByVal textReplace As String, ByVal newText As String)
            Dim myfileRd As StreamReader = File.OpenText(urlFile)
            Dim myfileWr As StreamWriter = File.CreateText("file.txt.out")
            Dim line As String = " "

            Do
                line = myfileRd.ReadLine()

                If line IsNot Nothing Then
                    line = line.Replace(textReplace, newText)
                    myfileWr.WriteLine(line)
                End If
            Loop While line IsNot Nothing

            myfileWr.Close()
            myfileRd.Close()
        End Sub
    End Class
End Namespace

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