2013-11-03 35 views
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中)并循环直到找到匹配的登录名。如果用户名错误,它会给出一个消息框(“无效的密码!”),如果它没有找到用户名或密码,那么它会给另一个(“失败的登录!”)。但是,我的问题是,当我运行代码时,如果详细信息是正确的,但如果它们不是,两个消息框出现(“无效密码”+“失败登录”),则登录工作正常,I知道这是因为循环继续,但我似乎无法制定出我想要的语法,任何帮助?

+0

你不是认真地存储密码明文的文本文件在生产应用程序是你吗? – Enigmativity

+0

@Enigmativity请在我的帖子中指出,我所说的不仅仅是个人用途。这是我正在学习的一项活动,没有什么是安全的。 – SCGB

+0

你也没有反过来说过。只要确保你不是,并且确保读者在生产系统中认为它没有问题。 – Enigmativity

回答

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 
1

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

If sline(0) = tbUsername.Text Then 
    MsgBox("Invalid password!") 
    Exit Do 
End 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 

最后,我真的希望这不是实际上应该是安全的或任何一个系统,因为没有被散列或盐腌进行用户登录一个纯文本文件的循环是不固定的一个非常好的方法你的申请。