说明:
输入时:姓氏,名字, ID#,班级和成绩。按"确定" 。按"加载" (输入的信息显示在下面的只读文本框中)。现在我再次输入,按"确定" 和"再次加载" (现在我看到两行信息)
会发生什么:
当我点击另存为时,将我的txt文件保存到某处并打开它。它将显示第一行的最后一个输入,以及secound上的空白(这似乎是第一个输入,但现在是空白)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace StudentGrades
{
public partial class Form1 : Form
{
static string status;
public Form1()
{
InitializeComponent();
writeButton.Enabled = false;
}
private void readButton_Click(object sender, EventArgs e)
{
using (StreamReader sr =
new StreamReader(@"C:\Users\User\Documents\Visual Studio 2017\Projects\StudentGrades\StudentGrades\TextFile.txt"))
{
textBoxReadGrades.AppendText(sr.ReadToEnd());
}
writeButton.Enabled = true;
}
private async void writeButton_Click(object sender, EventArgs e)
{
using (SaveFileDialog sfd = new SaveFileDialog() { Filter =
"TextDocuments|*txt.", ValidateNames = true})
{
if (sfd.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(sfd.FileName))
{
await sw.WriteLineAsync(textBoxFirstName.Text +
" " + textBoxLastName.Text +
" " + textBoxID.Text +
" " + textBoxClass.Text +
" " + textBoxGrade.Text);
MessageBox.Show("You have successfully saved", "Message",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
private void okButton_Click(object sender, EventArgs e)
{
using (StreamWriter sw =
new StreamWriter(@"C:\Users\User\Documents\Visual Studio 2017\Projects\StudentGrades\StudentGrades\TextFile.txt"))
sw.WriteLine(textBoxFirstName.Text +
" " + textBoxLastName.Text +
" " + textBoxID.Text +
" " + textBoxClass.Text +
" " + textBoxGrade.Text + "\n");
status = StatusLabel.Text =
"Entry Saved";
writeButton.Enabled = false;
}
private void GetInfo (string fileName)
{
textBoxReadGrades.AppendText(File.ReadAllText(fileName));
}
private void ExitButton_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
答案 0 :(得分:1)
您可以使用AppendText方法将文本附加到现有文件而不是覆盖:
using (StreamWriter sw = File.AppendText(sfd.FileName))
{
...
}