0

I have made a product key system that has a textbox and when I hit activate it reads a txt file with active product keys and it checks to make sure the textbox text is the same as one of the active codes in a text file. However, if I enter an invalid code, it freezes to death! maybe a bad code? Here is my code:

    Dim code As String
    code = TextBox1.Text

    Try
        Dim sr As IO.StreamReader = New IO.StreamReader("C:\Users\Chris\test.txt")
        Dim line As String

        Do
        line = sr.ReadLine

        Loop Until line = code
        sr.Close()
        my.settings.registered=True
        MsgBox("Your code is valid")

    Catch ex As Exception
        MsgBox("You have entered an invalid code, please try again", MsgBoxStyle.Critical)



    End Try
4

2 回答 2

1

您没有检查是否已到达文件末尾,因此您的应用程序可能会引发您未捕获的异常。您需要检查是否已到达流的末尾:

Do Until sr.EndOfStream
    ....
Loop

应该修复它

注意:您还应该在完成后处理您的 StreamReader 对象。但最好还是把它包装在一个Using块中,这样你就不必记住这样做了!

最好将所有这些包装成这样的函数:

Private Function IsValidCode(ByVal code As String) As Boolean
    Dim line As String
    Using sr As New StreamReader("yourfile")
        Do Until sr.EndOfStream
            line = sr.ReadLine
            If line = code Then Return True
        Loop
    End Using
    Return False
End Function
于 2013-05-28T15:18:54.233 回答
0

尝试改变你的循环..

Do
    line = sr.ReadLine

    if line = code then

      '.................
      exit do 

    end if

Loop Until line is Nothing
于 2013-05-28T15:29:28.883 回答