Help with reading in loop please?
I am trying to read in high scores from a text file that look like this
Name1
Score1
Name2
Score2
Name3
Score3
etc.
I can write them out fine, but reading them in I seem to be having a problem with. I have read in the first name ok but when I try to read in the second name, it is giving me the 3rd name. Code below
Code:
Dim objReader As IO.StreamReader = New IO.StreamReader("C:\Users\Karl\Desktop\HighScore.txt")
Dim strName As String
Dim intNumber As Integer
'Code for Name 1
lblName1.Text = objReader.ReadLine
lblName1.Visible = True
'Code for Name 2
intNumber = 0
Do Until intNumber = 2
objReader.ReadLine()
strName = objReader.ReadLine
intNumber = intNumber + 1
Loop
objReader.Close()
objReader.Dispose()
lblName2.Text = strName
lblName2.Visible = True
Can somebody please explain why lblName2 is becoming the fifth line of text instead of the third?
I realise I have probably not used the correct type of variables but I have only just started learning computing at college so don't bite my head off!
Thanks
Re: Help with reading in loop please?
When you first open the file stream, the position pointer points at the very beginning of the file. As you read data off the file, the pointer move along ahead pointing to the data to be read next.
Now you know how it works, go back to your code and count how many times you call the ReadLine method including how many time it's called in the loop (each time you call ReadLine, it reads 1 line and the pointer move to the next line)
Re: Help with reading in loop please?
Thankyou! I understood the principle of it, but I thought that when placed in a new function such as a loop, it would go back to the start of the file. I have it working now so thanks again
Re: Help with reading in loop please?
Quote:
Originally Posted by
Karl.Green
Thankyou! I understood the principle of it, but I thought that when placed in a new function such as a loop, it would go back to the start of the file. I have it working now so thanks again
It's good that you're able to figure it out and get it fixed :thumb: I just want to mention that you can reset the pointer to wherever you want it to be by setting the stream.position property. In your case, if you want to reset the pointer to the beginning of the file, you just need to set the streamreader.basestream.position = 0 and it's good to go.
Re: Help with reading in loop please?
Thanks again! Also it's great that you are giving a full explanation instead of just giving me code to copy and paste :)