Visual Basic Split()返回null

时间:2017-01-12 09:30:19

标签: vb.net file split

从文件中读取和拆分的代码:

Public Sub LoadAccount()
    currentfilereader = New StreamReader(filename)
    Dim Seperator As Char = " "c
    For count As Integer = 0 To NumUsers - 1
        textstring = currentfilereader.ReadLine
        Dim words() As String = currentfilereader.ReadLine.Split(Seperator)
        Username = words(0)
        Password = words(1)
        If words(2) = "1" Then
            AccessGranted = True
        Else
            AccessGranted = False
        End If
        Users(count, 0) = Username
        Users(count, 1) = Password
        Users(count, 2) = AccessGranted
    Next
    currentfilereader.Close()
End Sub

登录代码:

Public Sub Login()
    Dim InvalidUsername, InvalidPassword As Boolean
    InvalidUsername = True
    InvalidPassword = True
    LoginName = Form1.tbun.Text
    LoginPassword = Form1.tbpw.Text
    For count As Integer = 0 To NumUsers - 1
        If LoginName = Users(count, 0) Then
            InvalidUsername = False
            If LoginPassword = Users(count, 1) Then
                InvalidPassword = False
                CurrentUsername = LoginName
                CurrentPassword = LoginPassword
                CurrentAccessGranted = Users(count, 2)
                loggedin = True
            Else
                MsgBox("Invalid Password")
            End If
        Else
            MsgBox("Invalid Username")
        End If
    Next
End Sub

计算用户数的代码:

Public Sub NumberOfUsers()
    currentfilereader = New StreamReader(filename)
    NumUsers = File.ReadAllLines("Accounts.txt").Length
    MsgBox("There are " & NumUsers & " users")
End Sub

我添加了一个MsgBox来显示用户数,以确保所有工作正常,返回值2,因为我目前在文本文件中有2行," aa 1&# 34;和" b b 1"。

但是当此行运行Dim words() As String = currentfilereader.ReadLine.Split(Seperator)时,它返回null。

从计数中的NumUsers中减去1的目的是因为计数与数组一起从零开始。这意味着,如果我没有,如果文件中只有2个用户,则会检查3次。但我似乎无法弄清楚出了什么问题,以及为什么它会返回null。

1 个答案:

答案 0 :(得分:0)

您为每位用户致电ReadLine两次:

textstring = currentfilereader.ReadLine
Dim words() As String = currentfilereader.ReadLine.Split(Seperator)

这意味着对于第一个用户,您读取了两行,而对于第二个用户,您没有读取任何内容,导致空的拆分数组。

替换

Dim words() As String = currentfilereader.ReadLine.Split(Seperator)

使用

Dim words() As String = textstring.Split(Seperator)