David Cole - Grammar Police David Cole - Grammar Police - 7 months ago 32
Vb.net Question

Reading TXT file line by line (VB 2010)

I have a program written to be a username/password creator, and there is a section that I am attempting to make that will determine whether the entered username is taken or not, and inform the user. It doesn't seem to be working. My code is as follows:

z = File.OpenText(a)
Do Until z.EndOfStream() = True
Dim password As String
password = CStr(z.ReadLine() & vbCrLf)
If password = TextBox1.Text Then
errors = errors + 1
msgPrompt = msgPrompt & "The username you entered, " & TextBox1.Text & " is already taken."
End If
If errors > 1 Then
TextBox5.Text = errors & " errors occured."
ElseIf errors = 0 Then
TextBox5.Text = "No errors!"
Else
TextBox5.Text = errors & " error occured."
End If

If errors >= 1 Then
Button2.Enabled = True
Else
Button2.Enabled = False
End If
Loop


The passwords are stored line by line in a .txt file, so basically I want the program to go over each entry one by one and see if it matches what the user entered. If I am doing something wrong, please inform me, I'd love to get this script working.

Answer

Assuming that the heading of your question is correct, your variables in your code are named incorrectly - This isn't vitally important, but it will confuse whoever comes back in 6 months to maintain the software. Also, when your code is running correctly, as all the usernames will be unique, there is no need to return the number of errors.

It is longer than your original code, but the TextExists function can be used to open the file of your choosing such as the password file and the username file - Though your usernames and password in this situation are better stored in the one file.

'Opens the file and if it contains the input text, returns True. Otherwise returns false
Private Function TextExists(filename As String, inputText As String) As Boolean
    Dim z As StreamReader = File.OpenText(filename)
    Dim fileText As String
    Dim msgPrompt As String = ""
    Do Until z.EndOfStream() = True
        fileText = CStr(z.ReadLine())
        If inputText = fileText Then
            Return True
        End If
    Loop
    Return False
End Function

Private Sub CheckUserName()
    If TextExists(a, TextBox1.Text) Then
        MessageBox.Show("Username Already Exists")
        Button2.Enabled = False
    Else
        Button2.Enabled = True
    End If
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    CheckUserName()
End Sub

For serious storage of passwords the username and passwords should be encrypted before they are saved of course, and decrypted when loaded. Saving sensitive information like this in plain text is always a very bad idea.

Comments