我正在使用C#,WPF并且有一个关于游戏多项选择的作业,它有一个应用程序,为用户列出问题和答案。我想在file.text中写一次不仅仅是一次。
我用过这个事件:
此代码:
private void Button_Click(object sender, RoutedEventArgs e)
{
using( StreamWriter File = new StreamWriter(@"C:\Users\Admin\Documents\Visual Studio 2013\Projects\ĐỒ ÁN 2\ĐỒ ÁN 2\bin\Debug\Bo1.txt"))
{
File.WriteLine("dsCauHoi*Câu hỏi thêm*"+ txbcauhoi.Text.ToString()+ "*"+txbA.Text.ToString()+ "*"+ txbB.Text.ToString()+ "*" +txbC.Text.ToString() +"*"+ txbD.Text+ "*"+ txbAD.Text.ToString()+"/n");
}
MessageBox.Show("Cảm ơn bạn đã đóng góp ý kiến");
this.Close();
}
但它允许写一次。
答案 0 :(得分:5)
您需要附加到该文件,而不是重新创建(默认),
使用public StreamWriter(string path, bool append)构造函数重载附加到文件。 (只需在构造函数参数中添加一个true)
private void Button_Click(object sender, RoutedEventArgs e)
{
var filename = @"C:\Users\Admin\Documents\Visual Studio 2013\Projects\ĐỒ ÁN 2\ĐỒ ÁN 2\bin\Debug\Bo1.txt";
using(StreamWriter File = new StreamWriter(filename, true)) // true for append..
{
File.WriteLine("dsCauHoi*Câu hỏi thêm*"+ txbcauhoi.Text.ToString()+ "*"+txbA.Text.ToString()+ "*"+ txbB.Text.ToString()+ "*" +txbC.Text.ToString() +"*"+ txbD.Text+ "*"+ txbAD.Text.ToString()+"/n");
}
MessageBox.Show("Cảm ơn bạn đã đóng góp ý kiến");
this.Close();
}
答案 1 :(得分:3)
检查StreamWriter
构造函数方法的签名。
您只将文本文件物理地址传递给StreamWriter
。因此,默认情况下,StreamWriter会覆盖您的文本文件。传递true以追加StreamWriter构造函数方法的参数,如下所示。
using(StreamWriter File = new StreamWriter(@"C:\Users\Admin\Documents\Visual Studio 2013\Projects\ĐỒ ÁN 2\ĐỒ ÁN 2\bin\Debug\Bo1.txt", true))
{
File.WriteLine("dsCauHoi*Câu hỏi thêm*"+ txbcauhoi.Text.ToString()+ "*"+txbA.Text.ToString()+ "*"+ txbB.Text.ToString()+ "*" +txbC.Text.ToString() +"*"+ txbD.Text+ "*"+ txbAD.Text.ToString()+"/n");
}
MessageBox.Show("Cảm ơn bạn đã đóng góp ý kiến");
this.Close();