StreamReader - 从行读取

时间:2010-10-13 12:31:21

标签: vb.net

我有以下代码;

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

我现在要做的是将文件的所有奇数行(播放器名称)和偶数行读入两个单独的列表框中,我将如何处理?

我需要修改;

Using reader As StreamReader = New StreamReader("file.txt")
            ' Read one line from file
            line = reader.ReadLine
        End Using

我使用了以下解决方案之一但无法使其正常工作:(

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

4 个答案:

答案 0 :(得分:4)

您可以使用Mod运算符:

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

这种方法也适用于不是偶数/奇数模式,而是另一些重复的情况。假设每个玩家有3行:

player name 1
score 1
avatar url 1
player name 2
score 2
avatar url 2
...

然后,您可以使用Mod和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

答案 1 :(得分:2)

如果您可以可靠地预期文件中会有偶数行,那么您可以通过一次读取两行来简化这一行。

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

答案 2 :(得分:1)

我真的不知道VB的语法,但是像这样:

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

答案 3 :(得分:0)

另一种可能性是将整个文件作为一个块读入一个字符串,然后在vbcrlf上将该字符串SPLIT

    Dim buf = My.Computer.FileSystem.ReadAllText(Filename)
    Dim Lines() = Split(Buf, vbcrlf)

然后,行将包含文件中的所有行,索引。

所以你可以通过它们来获取每个玩家和他的其他信息。

 For x = 0 to ubound(Lines)
       'do whatever with each line
 next        

如果文件是巨大的,你不一定要这样做,但对于小文件,它是一种快速简便的处理方式。