我正在制作一个测验应用程序,该应用程序允许用户注册和登录该应用程序。用户的详细信息存储在文本文件中,并且我有一个允许用户更改其用户名的表格。我不知道如何仅覆盖文本文件
中的用户名我的问题是我不知道如何仅替换一个用户的密码和用户名,因为多个用户可以使用相同的密码。我已经尝试在Stack Overflow和Web中寻找解决方案,我没有发现与我的问题类似的东西。我当前的代码将每个用户的密码替换为相同的密码,例如,我的文本文件中的多个用户的密码为password123。
private void btnUpdateUserDetails_Click(object sender, EventArgs e)
{
string oldusername = txtBoxoldUsername.Text;
string newusername = txtBoxnewUsername.Text;
string oldpassword= txtBoxoldPassword.Text;
string newpassword = txtBoxnewPassword.Text;
string confirmedpassword = txtBoxConfirmedPassword.Text;
if ((!string.IsNullOrEmpty(oldusername)) && (!string.IsNullOrEmpty(newusername))
&& (!string.IsNullOrEmpty(oldpassword)) && (!string.IsNullOrEmpty(newpassword)) && (!string.IsNullOrEmpty(confirmedpassword)))
{
if ((!oldusername.Contains("~")) || (!newusername.Contains("~")))
{
if (newpassword == confirmedpassword)
{
if (File.Exists("users.txt"))
{
string[] users = File.ReadAllLines("users.txt");
bool userFound = false;
foreach (string user in users)
{
string[] splitDetails = user.Split('~');
string username = splitDetails[1];
string password = splitDetails[2];
if ((txtBoxoldUsername.Text == username) && (txtBoxoldPassword.Text == password))
{
string text = File.ReadAllText("users.txt");
text = text.Replace(oldusername, txtBoxnewUsername.Text).Replace(oldpassword, txtBoxnewPassword.Text);
File.WriteAllText("users.txt", text);
MessageBox.Show("Username and Password Updated Successfully!",
"Tas");
txtBoxoldUsername.Text = "";
txtBoxnewUsername.Text = "";
txtBoxoldPassword.Text = "";
txtBoxnewPassword.Text = "";
txtBoxConfirmedPassword.Text = "";
break;
}
else
{
MessageBox.Show("User details are incorrect",
"Incorrect details entered");
}
}
}
else
{
MessageBox.Show("No users have been registered", "No users");
}
}
else
{
MessageBox.Show("New Passwords don't match",
"Incorrect Details");
}
}
else
{
MessageBox.Show("Username must not contain any special characters i.e. ~", "~ entered");
}
}
else
{
MessageBox.Show("Please ensure all data is entered into the fields",
"Details missing");
}
}
private void btnBack_Click(object sender, EventArgs e)
{
this.Hide();
var homeForm = new HomeForm();
homeForm.Closed += (s, args) => this.Close();
homeForm.Show();
}
}
}