我做了一个产品密钥系统,有一个文本框,当我点击激活它读取具有活动产品密钥的文本文件,并检查以确保文本框文本与文本文件中的活动代码之一相同。但是,如果我输入一个无效的代码,它就会死机!也许是错误的代码?下面是我的代码:
Dim code As String
code = TextBox1.Text
Try
Dim sr As IO.StreamReader = New IO.StreamReader("C:UsersChristest.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
您没有检查是否已到达文件的末尾,因此您的应用程序可能会抛出您未捕获的异常。您需要检查是否到达了流的末尾:
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
试着改变你的循环…
Do
line = sr.ReadLine
if line = code then
'.................
exit do
end if
Loop Until line is Nothing