The best way to do this is to do a .ReadToEnd() to read the whole file in, and then .Split it once you have it in a string.
So, something like this (from a recent project I did)
-
Dim sr As New StreamReader("C:\dev\test.txt")
-
Dim read As String = sr.ReadToEnd()
-
Dim lines() As String = read.Split(vbCrLf)
-
For Each line As String In lines
-
MessageBox.Show(line)
-
Next
-
I'd say that the current code isn't too far from correct... a couple of changes:
Firstly, in your While clause, you're saying:
While sr.Readline <> Nothing; This is causing the software to read the next available line. Then immediately after that, you're asking your software to read another line into a variable. So:
While sr.ReadLine = Nothing 'Read the next available line and move read cursor.
Dim current As String = sr.ReadLine - now we're reading another line, without doing anything with the line we read in the While declaration. Make sense?
I would make 2 slight changes to your code if it were me writing it:
While Not sr.EndOfStream
Dim sCurrentLine = sr.ReadLine()
MsgBox sCurrentLine
End While
I'd hazard a guess that currently something is tripping his loop up so it thinks that line 4 returns nothing. Maybe the line is blank. Maybe somehow the file is corrupt.
Unless you're actually using your "i" counter, don't even bother with it. With a "For...Next", you don't need a counter, declared other than in the For declaration. i.e. something like:
For i = 0 To sr.LastLineIndex() 'That's pseudo code, there's really no LastLineIndex() method, I'm just demonstrating a concept where your counter would be useful. Really, you should pick the right tool for the right job, and unless you really need to know what i is, I'd say stick with your While loop and ditch the counter variable as it's surplus to requirement.
In a "For Each...Next" an iterator is automatically implied, so you don't even need a counter... but if you need to know which line you're currently at, then you'll need to handle that with a separate variable. If this is the case, I'd really suggest a For...Next loop, rather than a For Each...Next. When you're looking for a specific event such as an end of file, you don't need a counter unless you need to know what iteration you are currently at - for instance if you need the line number.
In this situation, I'd say you're using the right loop type, you're just not implementing it quite correctly.