overwriting a certain line of the txt file

0

I am making a code where I need to delete a certain line in a text file ( .txt ) and put something else on that line, I would like to know how I can do it.

Example: delete 2 line admin and type userNew

  

    
asked by anonymous 28.05.2018 / 23:10

1 answer

1

You can use something like:

private void ChangeUser(string currentUser, string newUser, int position)
{
    string sourceFile = @"C:\Test\root.txt";

    string[] lines = File.ReadAllLines(sourceFile);

    if(lines.Length == 0)
    {
        MessageBox.Show("Seu arquivo está vazio!");
        return;
    }

    using (StreamWriter writer = new StreamWriter(sourceFile))
    {
        for (int i = 0; i < lines.Length; i++)
        {
            // Verifica se é a segunda linha e se o conteúdo da mesma é igual ao usuário atual
            if(i == position && lines[i] == currentUser)
            {
                writer.WriteLine(newUser);
            }
            else
            {
                writer.WriteLine(lines[i]);
            }
        }
    }
}

Where currentUser is the user you want to replace, newUser is the new user and position is what line to look for the previous data in.

In your case, currentUser is "admin", newUser is "userNew" and position is 1, due to the fact that array starts at position 0, so the second position is 1.

    
29.05.2018 / 00:01