user770022
user770022

Reputation: 2959

Append to text file

I would like for my text file that gets created keeps being added to. As of right now its recreated everytime. Which is no good since I want to create a comma delimited text file with stored enters.

private void button1_Click(object sender, EventArgs e)
{
    WriteText();
    Reset();
}
public void WriteText()
{
    using (var writer = File.CreateText("filename.txt"))  
    {
        writer.WriteLine($"First name: {textBox1.Text} Lastname: {textBox2.Text} Phone: {textBox3.Text} Day of birth: {textBox4.Text}");
    }
}
public void Reset() => textBox1.Text = textBox2.Text = textBox3.Text = textBox4.Text = "";

Upvotes: 1

Views: 4074

Answers (4)

vamyip
vamyip

Reputation: 1171

It's easy. Try this:

public void writetext()
{
    using (TextWriter writer = new StreamWriter("filename.txt", true))  // true is for append mode
    {
        writer.WriteLine("First name, {0} Lastname, {1} Phone,{2} Day of birth,{3}", textBox1.Text, textBox2.Text, maskedTextBox1.Text, textBox4.Text);
    }
}

Upvotes: 5

Shadow Wizzard
Shadow Wizzard

Reputation: 66398

You can also have:

File.AppendAllLines("filename.txt", new string[] { 
    string.Format("First name, {0} Lastname, {1} Phone,{2} Day of birth,{3}", 
       textBox1.Text, textBox2.Text, maskedTextBox1.Text, textBox4.Text) 
});

This will save you using Writer altoghether and handle everything behind the scenes.

Upvotes: 0

Donald
Donald

Reputation: 1738

Instead of calling File.CreateText you should call File.AppendText. However, you should check to first see if the file exists using File.Exists

Here's some pseudo code:

if (File.Exists(path))
    writer = File.AppendText(path);
else
    writer = File.CreateText(path);

Upvotes: 2

McKay
McKay

Reputation: 12624

There is a

File.AppendText()

method.

Upvotes: 0

Related Questions