Search code examples
c#filetextlines

C# how to write multiple lines in a text file?


I am trying to press a button that takes the text from textbox4 and textbox5 to write it to a text file. BUT when I press it again to add new info to the text file it just replaces the old text in with the new. How do I get it to write another line below the first one each time I press the button?

This is the code I have so far

    private void button5_Click(object sender, EventArgs e)
    {
        try
        {
            xuidspath = @"c:\xuids.txt";
            ListViewItem lvi = new ListViewItem();
            lvi.Text = textBox4.Text;
            lvi.SubItems.Add(textBox5.Text);
            listXuid.Items.Add(lvi);
            TextWriter xuids = new StreamWriter(xuidspath);
            xuids.WriteLine(textBox4.Text + "-" + textBox5.Text);
            textBox5.Clear();
            textBox4.Clear();
            xuids.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

Any ideas?


Solution

  • Open the file for append.

    FileStream xuids = new FileStream(xuidspath, FileMode.Append);