我有以下代码:
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,如果用户单击login,则代码将打开我的users.txt文件(在strUsersPath中)并循环直到找到匹配的登录。如果用户名错误,它会给出一个消息框(“密码无效!”),如果找不到用户名或密码,那么它会给另一个(“登录失败!”)。
但是,我的问题是,当我运行代码时,如果细节正确,则登录工作正常,但如果不是,则两个消息框都出现,(“无效密码”+“登录失败”),我知道这是因为循环继续,但我似乎无法弄清楚我想要的语法,任何帮助?
答案 0 :(得分:1)
当您遇到导致您需要停止处理文件的情况时,请调用Exit Do.如果已经知道答案(有效登录或密码无效)
,这将阻止循环完全覆盖您的文件If sline(0) = tbUsername.Text Then
MsgBox("Invalid password!")
Exit Do
End If
此外,您的第二个If条件是多余的。当行无效时,循环将结束,因此您可以阻止检查每次迭代并将其放在循环之后。到达那里的唯一方法是登录无效。
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
最后,我真的希望这不是一个实际上应该是安全的系统或任何东西,因为为没有散列或加盐的用户登录循环纯文本文件不是保护应用程序的一种非常好的方法。 / p>
答案 1 :(得分: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