how can i write line by line in txt data? [closed]
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.Writ开发者_开发问答eLine(textBox1.Text);
tw.Close();
}
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);
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);
OR
using (StreamWriter sw = File.AppendText(fileName))
{
sw.WriteLine(line);
}
精彩评论