Click here to Skip to main content
15,891,951 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to read a text file that contain some distinctive keywords, so far I am able to read and replace the keywords on 1 line, but I don't know how to read and replace all the keywords in the text file..?

My text file looks like this, where $name, $lastname & $dob are the keywords to be replaced:

=================================
The persons name is: $name
The lastname is: $lastname
Date of Birth: $dob
=================================

My code so far is:

VB
Dim strFile As String = "c:\test.txt"
Dim strRead As StreamReader = File.OpenText(strFile)
Dim strX As String

        Do Until strRead.Peek = -1

            strX = strRead.ReadToEnd.Replace("$name", dt.Rows(0)("name"))
           ' strX = strRead.ReadToEnd.Replace("$lastname", dt.Rows(0)("lastname"))

            tbConfig.Text = strX

        Loop
Posted
Comments
grandanet 24-Apr-15 12:18pm    
Awesome, Yes! Thank you guys, both solutions work but the one provided by duDE makes it easier to the eyes.

To do multiple changes, you would need to do something like this:
VB
strX = strRead.ReadToEnd.Replace("$name", dt.Rows(0)("name"))
strX = strX.Replace("$lastname", dt.Rows(0)("lastname"))
strX = strX.Replace("$dob", dt.Rows(0)("dob"))
 
Share this answer
 
Instead of

VB
'strX = strRead.ReadToEnd.Replace("$name", dt.Rows(0)("name"))


use something like:

VB
strX = strRead.ReadToEnd()
strX = strx.Replace("$name", dt.Rows(0)("name"))
strX = strx.Replace("$lastname", dt.Rows(0)("lastname"))
strX = strx.Replace("$dob", dt.Rows(0)("dob"))


Another one possibility (if text is very long for example) is to read it line-by-line like this:

VB
Dim line As String = Nothing

Do Until strRead.Peek = -1
        line = reader.ReadLine()
        ' and so long
 
Share this answer
 
v5
Comments
grandanet 24-Apr-15 11:12am    
I tried using "reader.ReadLine()" before but it will only do changes on 1 line, now if I use "reader.ReadToEnd()" it reads completely and I think I have a better chance of reusing the "keywords" through the document. Right?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900