Home > Mobile >  How can i print a new line in a text file, each time i press a button?
How can i print a new line in a text file, each time i press a button?

Time:04-18

I coded a button to add input as a string to a text file , but i want to add a string to the file each time the button is being press, as it is rigth now my program overwrites the old string in the file.

Code for button :

 private void BtnRegister_Click(object sender, EventArgs e)
        {
            username = txtUsername.Text;
            password = txtPassword.Text;


            using (StreamWriter writer = new StreamWriter(path))
            {
                writer.WriteLine(username   ' '   password);
            }


        }

CodePudding user response:

Use this overload of the StreamWriter constructor.

    using (StreamWriter writer = new StreamWriter(path, append: true))
    {
        writer.WriteLine(username   ' '   password);
    }

CodePudding user response:

As msdn says about File.AppendAllText:

Appends the specified string to the file, creating the file if it does not already exist.

So as an alternative you can use File.AppendAllText:

File.AppendAllText("yourFile.txt", DateTime.Now.ToString());

Or if you want to have a newline

File.AppendAllText("yourFile.txt", 
                   DateTime.Now.ToString()   Environment.NewLine);
  • Related