I often come across various postings in different forums asking for simple things like reading information from text file and parsing data from the text. Well, I get kind of tired of answering those question so I decided to write a blog about it and then point them to the blog. So here it is.
Now the text file named C:\Test.txt I have two simple line:
and I want to grab "Brian" & "Dao" out to use for some other purpose. The code is listed below:
Dim mySR As System.IO.StreamReader
Dim myFirstName, myLastName, myTempStr As String
mySR = System.IO.File.OpenText("C:\Test.txt")
If Not mySR.EndOfStream Then
myTempStr = mySR.ReadLine
myFirstName = Mid(myTempStr, InStr(myTempStr, "Firstname:", CompareMethod.Text) + 10)
myTempStr = mySR.ReadLine myLastName = Mid(myTempStr, InStr(myTempStr, "Lastname:", CompareMethod.Text) + 9)
txtOutput.Text = myFirstName & vbCrLf & myLastName
mySR.Close()mySR = Nothing
Note that this doesn't take care of the leading space which could be trimmed by:
myTempStr = Trim(myTemStr)
Another way of accomplishing the same thing would be to call the Replace method and pass in the required parameters. The code sample below show two different ways you can call the Replace medhod.
myFirstName = Replace(myTempStr, "FirstName:", "", , , CompareMethod.Text)
myFirstName = myTempStr.Replace("FirstName:", "")
For those who are new to all this, be sure to look up the following string processing methods: InStr, InStrRev, Replace, Mid.