0

我有以下代码:

Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
    Using sr As New StreamReader(strUsersPath)
        Dim line = sr.ReadLine
        Dim sline As String()
        Do While (Not line Is Nothing)
            sline = line.Split("|")
            If sline(0) = tbUsername.Text And sline(1) = tbPassword.Text Then
                Form2.Show()
                Me.Hide()
                Exit Sub
            Else
                line = sr.ReadLine
                If sline(0) = tbUsername.Text Then
                    MsgBox("Invalid password!")
                End If
                If line = Nothing Then
                    MsgBox("Failed login")
                End If
            End If
        Loop
        End Using

End Sub  

我一直在尝试将此代码用于我的登录框,我有两个文本框,tbUsername 和 tbPassword,如果用户单击登录,则代码将打开我的 users.txt 文件(在 strUsersPath 中)并循环直到找到匹配的登录. 如果用户名错误,它将给出一个消息框(“无效密码!”),如果找不到用户名或密码,则会给出另一个消息框(“登录失败!”)。

但是,我的问题是,当我运行代码时,如果详细信息正确,则登录工作正常,但如果不是,则两个消息框都会出现(“无效密码”+“登录失败”),我知道这是因为循环继续,但我似乎无法找出我想要的语法,有什么帮助吗?

4

2 回答 2

1

当您遇到导致您需要停止处理文件的情况时,请调用 Exit Do。如果它已经知道答案(有效登录名或无效密码),这将防止循环完全遍历您的文件

If sline(0) = tbUsername.Text Then
  MsgBox("Invalid password!")
  Exit Do
End If

此外,您的第二个 If 条件是多余的。当 line 为空时,循环将结束,因此您可以防止检查每次迭代并将其放在循环之后。到达那里的唯一方法是登录无效。

Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
    Using sr As New StreamReader(strUsersPath)
        Dim line = sr.ReadLine
        Dim sline As String()
        Do While (Not line Is Nothing)
            sline = line.Split("|")
            If sline(0) = tbUsername.Text And sline(1) = tbPassword.Text Then
                Form2.Show()
                Me.Hide()
                Exit Sub
            Else
                line = sr.ReadLine
                If sline(0) = tbUsername.Text Then
                    MsgBox("Invalid password!")
                End If
            End If
        Loop
        End Using
     MsgBox("Invalid Login")
End Sub

最后,我真的希望这不是一个实际上应该是安全的系统或任何东西,因为循环纯文本文件用于未散列或加盐的用户登录并不是保护应用程序的好方法。

于 2013-11-03T21:53:19.420 回答
0

这是另一种方法:

Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
    Using sr As New StreamReader(strUsersPath)
        Dim line As String = sr.ReadLine
        Do While Not IsNothing(line)
            If line.StartsWith(tbUsername.Text & "|") Then
                If line = tbUsername.Text & "|" & tbPassword.Text Then
                    Form2.Show()
                    Me.Hide()
                Else
                    MsgBox("Invalid password!")
                End If
                Exit Sub
            End If
            line = sr.ReadLine
        Loop
    End Using
    MsgBox("Failed login")
End Sub
于 2013-11-03T23:46:26.123 回答