这让我很难过,因为我知道它为什么这么做,但我不知道如何阻止它;约翰|333。我的条件语句满足这两个条件,因为当它循环通过时,它拒绝一个用户并接受另一个用户,从而导致它执行if和else。请告诉我如何一次做一个。循环浏览文本,找到合适的用户,然后浏览条件。
Dim MyReader As New StreamReader("login.txt")
While Not MyReader.EndOfStream
Dim user As String = UsernameTextBox.Text + "|" + PasswordTextBox.Text
Dim names() As String = MyReader.ReadLine().Split()
For Each myName In names
If user = myName Then
Me.Hide()
OrderForm.Show()
Else
MsgBox("Wrong username and password")
End If
Next
End While
MyReader.Close()
这样的东西应该可以工作:
Using MyReader As New StreamReader("login.txt")
Dim GoodUser As Boolean = False
Dim user As String = UsernameTextBox.Text + "|" + PasswordTextBox.Text
While Not MyReader.EndOfStream
Dim user As String = UsernameTextBox.Text + "|" + PasswordTextBox.Text
Dim names() As String = MyReader.ReadLine().Split()
If Not names Is Nothing Then
For Each myName In names
If user = myName Then
GoodUser = True
Me.Hide()
OrderForm.Show()
Exit While
End If
Next
End If
End While
If Not GoodUser Then
MsgBox("Wrong username and password")
End If
End Using
使用块会自动处理流读取器。表示良好登录的布尔值可以在While循环退出时设置条件。当找到合适的用户时,Exit While将脱离循环。设置一个条件来检查空行通常是个好主意
有一件事需要注意。如果用户名中包含空格,则代码将无法工作。您必须限制用户名或使用不同的分隔符,如~
。
试试这个代码:
Using r As StreamReader = New StreamReader("login.txt")
Dim line As String = r.ReadLine
Dim user As String = UsernameTextBox.Text + "|" + PasswordTextBox.Text
Dim found As Boolean = False
Do While (Not line Is Nothing)
If (line = user) Then
found = True
break
End If
line = r.ReadLine
Loop
If (Not found) Then
MessageBox.Show("Wrong username and password")
End If
End Using