Anthony Cox Anthony Cox - 1 year ago 47 Question

Not fetching username and password from textfile

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim FILE_NAME As String = Cashierpath
System.IO.File.Exists(FILE_NAME) ' current
Dim objReader As StreamReader
Dim user As String = TextBox1.Text
Dim password As String = TextBox2.Text
Dim check As String

'Global Variable
'Dim DirPath7 As String = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Scrap Data\Cashier Info\Cashiers\")

For Each filename As String In IO.Directory.EnumerateFiles(DirPath7, "*.txt")
Dim fName As String = IO.Path.GetFileName(filename)
If user = fName & ".txt" Then
objReader = New StreamReader(fName)
check = objReader.ReadToEnd()
If password = check Then
MessageBox.Show("Welcome " & user & "!")
MessageBox.Show("Username or Password is incorrect")

End If
End If
End Sub

When the user enters their "username" and "password" into the textbox's, and clicks on this button, i want this button to check if there is a textfile with the name of the username entered, and if theres a file with that username it must then read it and check if the password matches the string inside the file. if it doesnt match it, it must then display a messagebox saying that "Username or password is incorrect", but nothing happens when i click on this button. No error message appears either.
Can someone take a look at my code and tell me what im doing wrong?

Answer Source

What you have there is an awful way to handle user credentials!

Regardless, you're way over-coding it.

Elsewhere in your app (correct use of Combine):

' Global Variable
Friend Shared DirPath7 As String = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Scrap Data", "Cashier Info", "Cashiers")

Button Handler:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim User As String = TextBox1.Text.Trim
    Dim Pass As String = TextBox2.Text.Trim

    ' Assemble the full expected file path, even if it might be malformed.
    ' The first case check protects against malformed path.
    Dim FilePath As String = IO.Path.Combine(DirPath7, String.Format("{0}.txt", User))

    Select Case True
        Case User.Length = 0
            MsgBox("Username is empty", vbExclamation, "Error")
        Case Pass.Length = 0
            MsgBox("Password is empty", vbExclamation, "Error")
        Case Not IO.File.Exists(FilePath)
            MsgBox("No file for User", vbExclamation, "Error")
        Case Not IO.File.ReadAllText(FilePath) = Pass
            MsgBox("Wrong Password", vbExclamation, "Error")
        Case Else
            MsgBox(String.Format("Welcome {0}!", User), vbOKOnly, "Success")
    End Select
End Sub