1

它一直返回 null,我希望有人可以为我清理它,看看是否有更简单的方法可以做到这一点。我真的很想开始制作我的游戏。

Public Class frmLogin

Private Sub mnuExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuExit.Click
    Application.Exit()
End Sub

Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
    Dim FILE_NAME As String = "C:\Users\Nick\documents\visual studio 2010\Projects\LoginFixed\Accounts\" + Me.txtCUser.Text
    If File.Exists(FILE_NAME) Then
        Me.lblExists.Text = "Username has already been created!"
        Return
    End If
    If txtCUser.Text.Length < 3 Then
        Me.lblExists.Text = "Must have atleast 3 characters."
        Return
    End If
    Dim writeFile As StreamWriter = File.CreateText("C:\Users\Nick\documents\visual studio 2010\Projects\LoginFixed\Accounts\" + Me.txtCUser.Text)
    writeFile.WriteLine("User: " + Me.txtCUser.Text) ' user
    writeFile.WriteLine("Pass: " + Me.txtCPass.Text) ' pass
    writeFile.WriteLine("-------------------")
    writeFile.Close()
End Sub

Private Function GetLine(ByVal fileName As String, ByVal line As Integer) As String
    Try
        If File.Exists(fileName) = False Then
            Using sr As New StreamReader("C:\Users\Nick\documents\visual studio 2010\Projects\LoginFixed\Accounts\" + Me.txtUser.Text)
                For i As Integer = 1 To line - 1
                    sr.ReadLine()
                Next
                Return (sr.ReadLine())
                sr.Close()
            End Using
        End If
    Catch ex As Exception
        Return ex.Message
    End Try
End Function

Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
        Dim FILE_NAME As String = "C:\Users\Nick\documents\visual studio 2010\Projects\LoginFixed\Accounts\" + Me.txtUser.Text
        If File.Exists(FILE_NAME) And Me.txtPassword.Text = (GetLine(FILE_NAME, 2).Substring(6)) Then
            Me.lblLoggedIn.Text = "Logged"
        ElseIf File.Exists(FILE_NAME) = False Then
            Me.lblLoggedIn.Text = "You must create an account! Navigate to TabPage2."
        End If
End Sub

结束类

这真的很有帮助。我不久前才开始使用vb,可能大约一两个星期。

4

1 回答 1

0

三件事。首先,在 GetLine() 中,如果文件不存在,您将尝试打开它;从 False 变为 True。其次,您应该打开传入的文件名,而不是使用来自 TextBox 的值的硬编码文件名。最后,要消除警告,如果文件不存在,您需要返回一些内容:

将 GetLine() 更改为:

Private Function GetLine(ByVal fileName As String, ByVal line As Integer) As String
    Try
        If File.Exists(fileName) Then
            Using sr As New StreamReader(fileName)
                For i As Integer = 1 To line - 1
                    sr.ReadLine()
                Next
                Return sr.ReadLine()
            End Using
        Else
            Return "{File Not Found: " & fileName & "}"
        End If
    Catch ex As Exception
        Return ex.Message
    End Try
End Function

*您将异常作为字符串返回,因此我遵循了该模型,但未找到文件错误。但是,如果您有实际错误,或者文件中的行是否与返回的“错误”完全相同,您怎么知道?

于 2013-05-12T03:37:59.703 回答