Home > Enterprise >  How to write multiple content into text file
How to write multiple content into text file

Time:12-03

I have a text file but I don't know how I can insert more than one item on it... This is my code:

    string path = @"data.txt";
    private void buttonInsert_Click(object sender, EventArgs e)
{
    FileStream fs = File.Create(path);
    StreamWriter sw = new StreamWriter(fs);          
    sw.Write(textBox1.Text);
    textBox1.Clear();
    sw.Close();
}

It only writes one time to the file, so If I type "Hi" and click the button it sends "Hi" to the file but if I type again on the texbox and click the button again it sends the new text and clears the other but I want to be adding multiple data not only 1 thing.

CodePudding user response:

Instead of Create() use AppendAllText(), which will also get you rid of the StreamWriter.

string path = @"data.txt";
private void buttonInsert_Click(object sender, EventArgs e)
{
    File.AppendAllText(path, textBox1.Text   Environment.NewLine);
    textBox1.Clear();
}

It's very convenient because

If the file does not exist, this method creates a file

  • Related