StreamReader - Reading from lines
I have the following code开发者_开发百科;
Public Sub writetofile()
' 1: Append playername
Using writer As StreamWriter = New StreamWriter("highscores.txt", True)
writer.WriteLine(PlayerName)
End Using
' 2: Append score
Using writer As StreamWriter = New StreamWriter("highscores.txt", True)
writer.WriteLine(Score)
End Using
End Sub
What I now want to do is read all the odd lines of the file (the player names) and the even lines into two separate list boxes, how would I go about that??
I need to modify;
Using reader As StreamReader = New StreamReader("file.txt")
' Read one line from file
line = reader.ReadLine
End Using
I have used one of the following solutions but cannot get it working :(
Public Sub readfromfile()
Using reader As New StreamReader("scores.txt", True)
Dim line As Integer = 0
While Not reader.EndOfStream
If line Mod 2 = 0 Then
frmHighScores.lstScore.Items.Add(line)
Else
frmHighScores.lstScore.Items.Add(line)
End If
line += 1
End While
End Using
End Sub
You can use the Mod
operator for this:
Using reader As New StreamReader("highscores.txt", True)
Dim line As Integer = 0
Dim text As String
Do
text = reader.ReadLine()
If text = Nothing Then
Exit Do
End If
If line Mod 2 = 0 Then
''# even line
Else
''# odd line
End If
line += 1
Loop
End Using
This approach also works for cases when it's not an even/odd pattern, but another number of repetions. Say you have 3 lines for each player:
player name 1
score 1
avatar url 1
player name 2
score 2
avatar url 2
...
Then you can get this pattern by using Mod
with 3
Dim subLine As Integer = line Mod 3
If subLine = 0 Then
''# player name
ElseIf subLine = 1 Then
''# score
Else
''# avatar url
End If
line += 1
If you can reliably expect there to be an even number of lines in the file, then you can simplify this by reading two at a time.
Using reader As StreamReader = New StreamReader("file.txt")
While Not reader.EndOfStream
Dim player as String = reader.ReadLine()
Dim otherInfo as String = reader.ReadLine()
'Do whatever you like with player and otherInfo
End While
End Using
I don't really know the syntax of VB but something like this:
dim odd as boolean = True
Using reader As StreamReader = New StreamReader("file.txt")
line = reader.ReadLine
if odd then
' add to list A
else
' add to list B
end
odd = Not Odd
End Using
Another possibility is to just read the whole file as a block into a single string and the SPLIT the string on vbcrlf
Dim buf = My.Computer.FileSystem.ReadAllText(Filename)
Dim Lines() = Split(Buf, vbcrlf)
Then, lines will contain all the lines from the file, indexed.
So you could step through them to get each player and his other info.
For x = 0 to ubound(Lines)
'do whatever with each line
next
If the file was HUGE, you wouldn't necessarily want to do it this way, but for small files, it's a quick and easy way to handle it.
精彩评论