如果来自数组BEFORE else语句的条件执行,则VB.Net满足

时间:2013-12-17 12:31:17

标签: vb.net if-statement

这是在杀我,因为我知道它为什么这样做但我不知道如何制止它。我正在阅读一个文本文件,我在2行中有2个用户:bill | 777&约翰| 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()

2 个答案:

答案 0 :(得分:0)

试试这段代码:

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

答案 1 :(得分:0)

这样的事情应该有效:

    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

using块自动处理streamreader。表示良好登录的布尔值可以在While循环退出时设置条件。当找到合适的用户时,Exit While将退出循环。设置条件以检查空行通常是个好主意

有一点需要注意。如果用户名包含空格,则代码将无法使用。您必须限制用户名或使用其他分隔符,如~