0

I'm trying to take the data from two text boxes, and writing it to file without replacing the current stuff already there when a button is pressed. This is what I have so far:

private void button1_Click_1(object sender, EventArgs e)
    {
        using (StreamWriter sw1 = new StreamWriter("DataNames.txt"))
        {
            sw1.WriteLine(textBox1.Text);
        }

        using (StreamWriter sw2 = new StreamWriter("DataNumbers.txt"))
        {
            sw2.WriteLine(textBox2.Text);
        }    
    }

Right now it takes the input, and replaces whatever is currently in the files so then there is only one line, instead of just adding it to the list. Thanks for the help.

b13rg
  • 480
  • 6
  • 15

5 Answers5

4
//using (StreamWriter sw1 = new StreamWriter("DataNames.txt"))
//{
//   sw1.WriteLine(textBox1.Text);
//}
System.IO.File.AppendAllText("DataNames.txt", textBox1.Text);
H H
  • 263,252
  • 30
  • 330
  • 514
2

Use StreamWriter Constructor (String, Boolean) constructor and pass true for append.

true to append data to the file; false to overwrite the file. If the specified file does not exist, this parameter has no effect, and the constructor creates a new file.

In your code pass true like:

using (StreamWriter sw1 = new StreamWriter("DataNames.txt",true))
user2711965
  • 1,795
  • 2
  • 14
  • 34
1

Try this

using (StreamWriter sw2 = new StreamWriter("DataNumbers.txt", true))
{
    sw2.WriteLine(textBox2.Text);
}

Second argument true tells that file needs to be appended instead of overwriting. StreamWriter(String, Boolean)

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
0

You are making two separate instance of stream writer, and they are both attempting to write to the same file, so they are competing with each other - that's why you are seeing the overwriting.

If you want to add text to the end of a file, the best way to do so is probably File.AppendAllText: http://msdn.microsoft.com/en-us/library/ms143356.aspx

private void button1_Click_1(object sender, EventArgs e)
{
    System.IO.File.AppendAllText("DataNames.txt", textBox1.Text + textBox2.Text);
}

AppendAllText is quite useful if you are doing small, relatively infrequent appends as you can just send strings into it without thinking as opposed to making sure you are using your stream writer.

User
  • 1,118
  • 7
  • 23
0

Switch the

new StreamWriter("DataNumbers.txt")

to

File.CreateText("DataNames.txt")

You can find more info at:

http://msdn.microsoft.com/en-us/library/system.io.file.appendtext.aspx

Chris
  • 257
  • 2
  • 14