如何创建记录登录详细信息的txt文件?VB.NET



我想创建一个txt文件,当按下"登录"按钮时,它存储用户名,密码,日期和时间以及用户类型。但我所知道的是如何创建一个 txt 文件。谁能帮我?这是我的登录按钮的代码:

Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
    Dim username As String = ""
    Dim password As String = ""
    Dim cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=D:Library Management SystemLMS_Database.accdb")
    Dim cmd As OleDbCommand = New OleDbCommand("SELECT ID_Number FROM Users WHERE ID_Number = '" & txtUsername.Text & "' AND ID_Number = '" & txtPassword.Text & "'", cn)
    cn.Open()
    Dim dr As OleDbDataReader = cmd.ExecuteReader()
    If (dr.Read() = True And cboUserType.Text = "Student") Then
        MsgBox("Welcome!", MsgBoxStyle.OkOnly, "Successfully logged in.")
        frmViewBooks.Show()
        txtUsername.Clear()
        txtPassword.Clear()
        cboUserType.SelectedIndex = -1
        Me.Hide()
    Else
        If (txtUsername.Text = "admin" And txtPassword.Text = "ckclibraryadmin" And cboUserType.Text = "Administrator") Then
            MsgBox("Welcome, admin!", MsgBoxStyle.OkOnly, "Successfully logged in.")
            frmAdminWindow.Show()
            txtUsername.Clear()
            txtPassword.Clear()
            cboUserType.SelectedIndex = -1
            Me.Hide()
        Else
            MsgBox("Your username or password is invalid. Please try again.", MsgBoxStyle.OkOnly, "Login failed.")
            txtUsername.Clear()
            txtPassword.Clear()
            cboUserType.SelectedIndex = -1
        End If
    End If
End Sub

我将从计时器获取日期和时间值。

Private Sub frmLogIn_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    tmrLogIn.Start()
End Sub
Private Sub tmrLogIn_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrLogIn.Tick
    lblTime.Text = DateTime.Now.ToString()
End Sub

谢谢!

我想

指出一些事情,也许以后可以帮助你。数据对象通常实现 iDisposable,最好将它们包装在 Using 语句中或手动释放它们。此外,将任何数据库代码包装到 Try/Catch 异常处理程序中通常是一个好主意,因为在您尝试访问外部数据的任何时候都可能出错。此外,参数化查询始终是一个好主意。最后,您只想验证是否从 SQL 语句返回了一行,因此您的 SQL 语句应该返回返回的行数,然后您可以使用 ExecuteScalar 获取返回的那一个值。

解决了所有这些问题,您需要做的就是使用 IO 将一行附加到文本文件中。File.AppendAllLines 方法使用您已有的数据(如果登录已验证(。

以下是实现我建议的所有内容的示例:

'Declare the object to return
Dim count As Integer = -1
'Declare the connection object
Dim con As OleDbConnection
'Wrap code in Try/Catch
Try
    'Set the connection object to a new instance
    con = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=D:Library Management SystemLMS_Database.accdb")
    'Create a new instance of the command object
    'TODO: If [Username] and [Password] are not valid columns, then change them
    Using cmd As OleDbCommand = New OleDbCommand("SELECT Count([ID_Number]) FROM [Users] WHERE [Username] = @username AND [Password] = @password", con)
        'Parameterize the query
        With cmd.Parameters
          .AddWithValue("@username", txtUsername.Text)
          .AddWithValue("@password", txtPassword.Text)
        End With
        'Open the connection
        con.Open()
        'Use ExecuteScalar to return a single value
        count = Convert.ToInt32(cmd.ExecuteScalar())
        'Close the connection
        con.Close()
    End Using
    If count > 0 Then
      'Append the data to the text file
      'TODO: Change myfilehere.txt to the desired file name and location
      IO.File.AppendAllLines("myfilehere.txt", String.Join(",", {txtUsername.Text, txtPassword.Text, DateTime.Now, cboUserType.Text}))
      'Check if it is a student or admin
      If cboUserType.Text = "Student" Then
        'Inform the user of the successfull login
        MessageBox.Show("Welcome!", "Login Successfull", MessageBoxButtons.OK)
        frmViewBooks.Show()
      ElseIf cboUserType.Text = "Administrator" Then
        'Inform the admin of the successfull login
        MessageBox.Show("Welcome, admin!", "Login Successfull", MessageBoxButtons.OK)
        frmAdminWindow.Show()
      End If
      'Reset and hide the form
      txtUsername.Clear()
      txtPassword.Clear()
      cboUserType.SelectedIndex = -1
      Me.Hi
    Else
      'Inform the user of the invalid login
      MessageBox.Show("Invalid username and/or password. Please try again.", "Invalid Login", MessageBoxButtons.OK)
    End If
Catch ex As Exception
    'Display the error
    Console.WriteLine(ex.Message)
Finally
    'Check if the connection object was initialized
    If con IsNot Nothing Then
        If con.State = ConnectionState.Open Then
            'Close the connection if it was left open(exception thrown)
            con.Close()
        End If
        'Dispose of the connection object
        con.Dispose()
    End If
End Try

您的目标可以通过多种方式实现。例如,您可以创建一个 access/sql/mysql 数据库来存储所需的信息。但是,如果要改用文本文件,则可以将用户名,密码和其他详细信息存储在单独的行中。然后,您可以从文本文件中读取每一行并按照您想要的方式使用它。那么,你更喜欢哪一个?数据库还是文本文件?发表评论,我会根据您的选择添加代码/说明

最新更新