c# - 如何多次写入文件文本?

标签 c# wpf

我正在使用 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();
}

但它允许写入一次。

最佳答案

您需要附加到文件,而不是重新创建它(默认)

使用 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();
}

关于c# - 如何多次写入文件文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37629423/

相关文章:

c# - 网络核心 : How to Simple Unit Test Repository and Service with Database Rows

c# - WCF 服务 : Publicly available services useful for testing

wpf - 如何手动触发 MahApps 动画

c# - WPF MoveFocus() 在 Vista 上工作,而不是 XP

c# - 如何将 json 字符串反序列化为域对象?

c# - Windows PE WinForm应用程序未执行

c# - 如何读取 HTML 文件并替换为我们的字符

wpf - 将两个 UserControl 绑定(bind)到同一个 DataContext 或 ViewModel?

c# - wpf mvvm 中的 Datagrid SelectedIndex 在 RaisePropertyChanged 上设置为 0

c# - 如何在不使用 INotifyPropertyChanged 的​​情况下更新 View 和 View 模型