简体   繁体   中英

How to override a specific line in a text file in c#

I have the following situation. I am creating a quiz game in c# visual studio and want to create a Register and Login forms. When a user registers a new account the text file will store their username and password and will set the high score to 0. Each line in the text file looks like that: username;password;highscore. ';' is the delimiter. I have created a new project to create a practice login/ register form. Here is my code for the register form:

 private void btnRegister_Click(object sender, EventArgs e)
    {
        if (txtPassword.Text == txtConfirmPassword.Text)
        {
            string newAccount = txtName.Text + ";" + txtConfirmPassword.Text + ";" + "0";
            TextWriter account = new StreamWriter("../../TextFile/LogonDetails.txt", true);
            account.WriteLine(newAccount);
            account.Close();
            MessageBox.Show("Account created");
        }

and here is my code for the login form

            string line = "";
        StreamReader myReader = new StreamReader("../../TextFile/LogonDetails.txt");
        string[] accounts = new string[900000]; int value = 0;
        while ((line=myReader.ReadLine()) != null)
        {
           string[] data = line.Split(';');
            if ((data[0] == txtLoginName.Text) && (data[1] == txtLoginPassword.Text) && (int.Parse(data[2]) > int.Parse(txtScore.Text))) 
            {
                value = 1;
                break;
            }
            if ((data[0] == txtLoginName.Text) && (data[1] == txtLoginPassword.Text) && (int.Parse(data[2]) < int.Parse(txtScore.Text)))
            {
                value = 2;
                break;
            }
            else
            {
                value = 3;
            }
        }
        if (value == 1)
        {
            MessageBox.Show("Your score remains the same");
        }
        else if (value == 2)
        {
            string updatedAccount = txtLoginName.Text + ";" + txtLoginPassword.Text + ";" + txtScore;
            TextWriter textAccounts = new StreamWriter("../../TextFile/LogonDetails.txt");
            textAccounts.WriteLine(updatedAccount);
            textAccounts.Close();
        }
        else if (value == 3)
        {
            MessageBox.Show("Account not found");
        }
    }

So my question is how can I override the line stored in the text file if in this case 'txtScore' is greater than data[2]? I have tried creating a new line each time the score is greater but that seems inefficient. Is there a way that i can override the line to change the score value? Any help is greatly appreciated

If the file is not that long you can do something like this:

  String fileName = @"C:\LogonDetails.txt";

  var data = File
    .ReadLines(fileName)
    .Select(line => line.Split(';'))
    .Select(items => {
       if ((items[0] == txtLoginName.Text) &&
           (items[1] == txtLoginName.Text) &&
           (int.Parse(items[2]) < int.Parse(txtScore.Text))) 
         items[2] = int.Parse(txtScore.Text);

       return items; 
     })
   .ToList(); // materialize in oreder to prevent file read/write collision

  File.WriteAllLines(fileName, data);

There is no straightforward way to target a specific line in a text file to update the contents on that line. I would suggest storing your information in an XML (structured data) format; .NET already has the capabilities built in for reading and writing to specific nodes in an XML file.

If you don't want to do that, then my suggestion would be that you load all the lines from the text file into memory as instances of, eg a User class that has as properties your username, password, and score, and then write them all back out to your data file all at once with any updates to the scores.

By the way, it's generally not a good idea to store passwords in plain text, so I would hope you're at least employing a hashing algorithm.

Well, based on your question you know the line number, so do something like this:

var lines = File.ReadAllLines(@"path to file"); 
if (lines.Contains("1234"))
{
 lines[Array.IndexOf(lines, "1234")] = "new york";
}
File.WriteAllLines(@"path to file", lines);

try like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM