Adam Gorski
Adam Gorski

Reputation: 69

Streamreader Error In Loop: Cannot access a disposed object. VB.NET

Help! When I Type A Password Wrong The Application Crashes With The Following Error: Cannot access a disposed object. The Code Is In VB.Net

Sub PassAuth()
    Dim checker As StreamReader = New StreamReader(WC.OpenRead(address))
    Do Until Authed = False


        readpass = checker.ReadLine

        If readline = "End" Then
            MsgBox("Incorrect Username 'Or Password", 0 + 16, "Error")
            Authed = False
            checker.Close()
            checker.Dispose()
            checker.ReadLine()
        ElseIf readline = usrbox.Text Then

            chekpass = checker.ReadLine


            If chekpass = passbox.Text Then
                Authed = False
                checker.Close()
                checker.Dispose()
                AccessGranted()
            End If

        End If
    Loop
    Authed = True
     checker.Close()
     checker.Dispose()

The Error Occurs When:

 chekpass = checker.ReadLine

I Never Disposed The Stream So Why Would The Happen.

EDIT: It Reads The Username File And If It Detects The Username It Will Start The PassAuth Sub. The PassAuth Sub Check every Line And If It Detects The Username It Checks The Next Line For The Password. If The Passwords Match It Won't Crash, If They Don't Match It Will Crash. If it doesn't detect any matching passwords it will hit the End Line. When It Does it Will Say Wrong Password. Here Is The UserAuth Sub:

Dim reader As StreamReader = New StreamReader(WC.OpenRead(address))
    Do Until usrauth = False

        readline = reader.ReadLine
        If readline = "End" Then
            UsrAuth = False
            MsgBox("Incorrect Username Or Password", 0 + 16, "Error")
            reader.Dispose()
            reader.Close()
        ElseIf readline = usrbox.Text Then
            UsrAuth = False
            reader.Dispose()
            reader.Close()
            PassAuth()


        End If
    Loop
     reader.Dispose()
    reader.Close()

Please Note That This Does Access A FTP Server.

Upvotes: 2

Views: 367

Answers (1)

Steve
Steve

Reputation: 216303

I would simplify your code with File.ReadAllLines()

Sub PassAuth()
    Dim lines = File.ReadAllLines(address)
    if lines(0) = usrbox.Text AndAlso lines(1) = passbox.Text Then
       AccessGranted()
    else
       MsgBox("Incorrect Username 'Or Password", 0 + 16, "Error")
    End If
End Sub

Upvotes: 1

Related Questions