VB.NET中如何实现点击登录按钮时记录登录信息至TXT文件?
Hey there! Let's get your login logging feature up and running. Here's how you can modify your existing VB.NET code to create a TXT file that stores the username, password, login timestamp, and user type whenever a successful login happens.
Step 1: Add a Helper Method for Writing to TXT
First, let's create a reusable subroutine to handle writing the log details to a file. This keeps your code clean and avoids repeating logic:
Private Sub WriteLoginLog(username As String, password As String, userType As String, loginTime As DateTime) ' Define the path for your log file (you can change this to your preferred location) Dim logFilePath As String = "D:\Library Management System\LoginLogs.txt" ' Format the log entry with all required details Dim logEntry As String = $"Username: {username}, Password: {password}, User Type: {userType}, Login Time: {loginTime.ToString("yyyy-MM-dd HH:mm:ss")}" ' Append the entry to the TXT file (creates the file if it doesn't exist) System.IO.File.AppendAllText(logFilePath, logEntry & Environment.NewLine) End Sub
Key Notes:
- File Path: Adjust
logFilePathto where you want the log file stored. Using the same directory as your database makes sense for organization. - Append Mode:
File.AppendAllTextensures each new login adds a new line instead of overwriting the existing file. - Timestamp Format: The
yyyy-MM-dd HH:mm:ssformat gives a clear, sortable datetime string—feel free to adjust this to your preference.
Step 2: Update the Login Button Code
Now, call this helper method in both successful login branches (Student and Administrator). We'll use DateTime.Now directly for the timestamp (no need to rely on the timer's label, since we can get the current time instantly when the login succeeds):
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click Dim username As String = txtUsername.Text.Trim() Dim password As String = txtPassword.Text.Trim() Dim userType As String = cboUserType.Text.Trim() Dim loginTime As DateTime = DateTime.Now Dim cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=D:\Library Management System\LMS_Database.accdb") ' Fixed your SQL query - you probably meant to compare Password field instead of ID_Number twice! Dim cmd As OleDbCommand = New OleDbCommand("SELECT ID_Number FROM Users WHERE ID_Number = @Username AND Password = @Password", cn) ' Use parameters to prevent SQL Injection (critical security improvement!) cmd.Parameters.AddWithValue("@Username", username) cmd.Parameters.AddWithValue("@Password", password) cn.Open() Dim dr As OleDbDataReader = cmd.ExecuteReader() If dr.Read() AndAlso userType = "Student" Then MsgBox("Welcome!", MsgBoxStyle.OkOnly, "Successfully logged in.") ' Call the log method here WriteLoginLog(username, password, userType, loginTime) frmViewBooks.Show() ClearLoginFields() Me.Hide() ElseIf username = "admin" AndAlso password = "ckclibraryadmin" AndAlso userType = "Administrator" Then MsgBox("Welcome, admin!", MsgBoxStyle.OkOnly, "Successfully logged in.") ' Call the log method here too WriteLoginLog(username, password, userType, loginTime) frmAdminWindow.Show() ClearLoginFields() Me.Hide() Else MsgBox("Your username or password is invalid. Please try again.", MsgBoxStyle.OkOnly, "Login failed.") ClearLoginFields() End If cn.Close() ' Don't forget to close the connection! End Sub ' Helper to clear login fields (reduces repetition) Private Sub ClearLoginFields() txtUsername.Clear() txtPassword.Clear() cboUserType.SelectedIndex = -1 End Sub
Important Improvements:
- Fixed SQL Query: Your original query was comparing both username and password to
ID_Number—I updated it to use aPasswordfield (adjust if your actual column name is different). - SQL Injection Protection: Added parameterized queries instead of string concatenation—this is a crucial security fix to prevent malicious attacks.
- Cleaner Code: Extracted field clearing to a separate
ClearLoginFieldssubroutine to avoid repeating the same lines. - Connection Cleanup: Added
cn.Close()to ensure the database connection is properly closed after use.
Step 3: Optional - Log Failed Logins (If Needed)
If you want to log failed login attempts too, just add a call to WriteLoginLog inside the Else block. You could even modify the log entry to note the failure, like:
' Modify the log entry in WriteLoginLog or create a separate failed log method Dim logEntry As String = $"FAILED LOGIN - Username: {username}, Password: {password}, User Type: {userType}, Attempt Time: {loginTime.ToString("yyyy-MM-dd HH:mm:ss")}"
内容的提问来源于stack exchange,提问作者Rey Anthony Abarquez Rosalado

