2013-12-17 99 views
0

這是殺了我,因爲我知道它爲什麼這樣做,但我不知道如何阻止它。我正在閱讀一個文本文件,其中有兩行用戶:777 & john | 333。 我的條件語句滿足這兩個條件,因爲當它循環時,它會拒絕一個用戶並接受另一個用戶,導致它執行if和else。請告訴我如何一次執行此操作。通過文本循環,獲取適當的用戶,然後通過條件。VB.Net滿足條件從數組BEFORE 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() 

回答

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 

的使用塊自動銷燬的StreamReader的。表示良好登錄的布爾值可以設置While循環退出時的條件。當找到合適的用戶時,Exit While將跳出循環。設置一個條件來檢查空行通常是一個好主意

有一點需要注意。如果用戶名包含空格,則代碼將不起作用。您必須限制用戶名或使用不同的分隔符,如~

+0

謝謝。這工作。我必須研究如果不是沒有名字,並得到更好的理解。對此,我真的非常感激。 – Addy75

+0

簡化if語句。它基本上意味着「如果名字是某種東西」。但是因爲沒有一個值表示我們使用'Not'來從'Is Nothing'中取反值。因此,如果名稱不是什麼,那麼If塊中的代碼都不會運行,但如果它不是什麼,那麼代碼將運行。 – tinstaafl

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

謝謝你的幫助。對此,我真的非常感激。 – Addy75