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

时间:2018-01-27 13:02:56

标签: vb.net

我想创建一个存储用户名,密码,日期和时间的文本文件。按下“登录”按钮时的时间和用户类型。但我所知道的是如何创建一个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 System\LMS_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

谢谢!

2 个答案:

答案 0 :(得分:1)

我想指出的一些事情可能会在以后帮助你。数据对象通常实现iDisposable,最好将它们包装在Using语句中或手动处理它们。此外,将任何数据库代码包装到Try / Catch异常处理程序中通常是个好主意,因为在您尝试访问外部数据的任何时候都可能出错。此外,parameterize your query总是一个好主意。最后,您只想验证从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 System\LMS_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

答案 1 :(得分:0)

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