如何将多个内容写入文本文件
How to write multiple content into text file
我有一个文本文件,但我不知道如何在其中插入多个项目...
这是我的代码:
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();
}
它只向文件写入一次,所以如果我键入“Hi”并单击按钮,它会将“Hi”发送到文件,但如果我再次在 texbox 上键入并再次单击按钮,它会发送新的文本并清除另一个,但我想添加多个数据,而不仅仅是一件事。
而不是 Create()
use AppendAllText()
,这也会让您摆脱 StreamWriter。
string path = @"data.txt";
private void buttonInsert_Click(object sender, EventArgs e)
{
File.AppendAllText(path, textBox1.Text + Environment.NewLine);
textBox1.Clear();
}
非常方便,因为
If the file does not exist, this method creates a file
我有一个文本文件,但我不知道如何在其中插入多个项目... 这是我的代码:
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();
}
它只向文件写入一次,所以如果我键入“Hi”并单击按钮,它会将“Hi”发送到文件,但如果我再次在 texbox 上键入并再次单击按钮,它会发送新的文本并清除另一个,但我想添加多个数据,而不仅仅是一件事。
而不是 Create()
use AppendAllText()
,这也会让您摆脱 StreamWriter。
string path = @"data.txt";
private void buttonInsert_Click(object sender, EventArgs e)
{
File.AppendAllText(path, textBox1.Text + Environment.NewLine);
textBox1.Clear();
}
非常方便,因为
If the file does not exist, this method creates a file