overwrite certain line of the txt file

Asked

Viewed 538 times

0

I’m making a code where I need to delete a particular line in a text file (.txt) and put something else on that line, I’d like to know how I can do that.

Example: delete 2 line admin and write user

inserir a descrição da imagem aqui

1 answer

2


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 which line the previous data should be searched for.

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

  • 1

    I got, thank you so much for helping :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.