StreamReader > Reading textfiles into Visual Studio

So what we wanna do in this little tut is to be able to load a text file from our local hard drive into visual basic,

i’ve got this text file that contains different players from a belgian soccer team , with there scores and player names…

Scores, TXT file

So this is what we will do after reading the text file:

We first filter out the team name , we only want the player scores…. , which is the last number in each textline…

Using the Streamreader we can read text files into the Visual Basic program, not as hard as you might think…

Here we go …

First we declare a new StreamReader

Dim fileReader As System.IO.StreamReader

We than provide the StreamReader the file location of our textfile

fileReader = My.Computer.FileSystem.OpenTextFileReader(“C:\test.txt”)

Following we declare a new String variable stringReader, TekstLijn and sSpeeldag

Dim stringReader As String
Dim sSpeeldag As String
Dim TekstLijn As String

Using the Do … Loop Until we run through the text file …

Do
stringReader = fileReader.ReadLine()
TekstLijn = stringReader
If TekstLijn.Length > 20 Then
Dim sInfo() As String
sInfo = TekstLijn.Split(vbTab) Dim sPunt As String
sPunt = sInfo(5)

MsgBox(“Score: ” & sPunt)

End If

Loop Until TekstLijn Is Nothing

What we actually do in the code above is running through each line of the textfile, we first check if the line we are currently at contains more than 20 characters, hereby we filter out the names of the soccer teams…

What we than do is split the whole line into different items, in this case we only need the player scores, …

So we will use the 5ft item of the split

sInfo(5)

After splitting the text line, we will use the MsgBox command to put the player score on the screen, and this for each textline in the textfile…

Easy afterall for those who didn’t know this function yet…

A StreamReader function is also available in Visial Studio, with this function we will be able to write to textfiles….

No comments yet

Leave a reply