views:

101

answers:

3

I try to write line by line data but. if i run my application. writng last text1 data in script.txt

private void button1_Click(object sender, EventArgs e)
{
   System.IO.TextWriter tw;
   tw = new StreamWriter("C:/Script.txt");
   tw.WriteLine(textBox1.Text);
   tw.Close();
}
+2  A: 

If you need to append line but not replace all contents then pass "true" as second parameter to constructor of StreamWriter:

tw = new StreamWriter("C:/Script.txt", true);
Yauheni Sivukha
+2  A: 

I think that for what you want to achieve (assuming you want to append each line to the end of the file), using File.AppenAllLines is the simplest way forward:

private void button1_Click(object sender, EventArgs e)
{
   File.AppendAllLines(@"C:\Script.txt", new[]{ textBox1.Text });
}

Alternatively, if you are not using .NET 4, you can use File.AppendAllText instead, adding a line feed to the end:

File.AppendAllText(@"C:\Script.txt", textBox1.Text + Environment.NewLine);
Fredrik Mörk
A: 

OR

using (StreamWriter sw = File.AppendText(fileName))
{
     sw.WriteLine(line);
}
Dan Vallejo