I am making a quiz application that allows users to register and login in to the application. The details for the users are stored in text files and I have a form which allows the user to change their usernames. I don't know how to override only the usernames in the text-file
my problem is that i don't know how to replace just the password and username for just one user because multiple users can have the same password.I have already tried to look for the solution both in Stack Overflow and the web and I did not find anything similar to my problem. my current code replaces the password for every user with the same password eg multiple users in my text file have password123 for their password.
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();
}
}
}