C# C将数据写入文本文件
我这里有一个家庭作业。我创建了一个表单,其中包含4个文本框,用于输入数据、帐户、名字、姓氏和余额。我有四个按钮,创建文件、将数据保存到文件、清除和退出。基本上,程序所做的就是创建一个文本文件,然后我将数据输入文本框,然后点击save data file(保存数据文件),将数据写入我创建的文本文件。“清除”和“退出”已经完成,我的程序正在创建文本文件,现在我只需要有人为我指明正确的方向,告诉我如何将输入的数据写入文本文件。这是我的密码,提前谢谢C# C将数据写入文本文件,c#,forms,C#,Forms,我这里有一个家庭作业。我创建了一个表单,其中包含4个文本框,用于输入数据、帐户、名字、姓氏和余额。我有四个按钮,创建文件、将数据保存到文件、清除和退出。基本上,程序所做的就是创建一个文本文件,然后我将数据输入文本框,然后点击save data file(保存数据文件),将数据写入我创建的文本文件。“清除”和“退出”已经完成,我的程序正在创建文本文件,现在我只需要有人为我指明正确的方向,告诉我如何将输入的数据写入文本文件。这是我的密码,提前谢谢 using System; using System
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 Chapter_17_Ex.Sample_1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCreate_Click(object sender, EventArgs e)
{
SaveFileDialog file = new SaveFileDialog();
file.FileName = "client.txt";
file.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
file.ShowDialog();
StreamWriter filewrite = new StreamWriter(file.FileName);
}
private void btnSave_Click(object sender, EventArgs e)
{
TextWriter file = new TextWriter
}
private void btnClear_Click(object sender, EventArgs e)
{
txtAccount.Clear();
txtBalance.Clear();
txtFirstName.Clear();
txtLastName.Clear();
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
创建StreamWriter实例的过程是正确的。现在要做的是使用该类的WriteLine方法。将StreamWriter实例包装到using块中也是一个好主意:
对于文件创建,您可以使用:
File.Create(file.FileName).Close(); // replace the StreamWriter code with this
要获取写入该文件的最简单方法:
string line = string.Join(",", txtAccount.Text, txtBalance.Text, txtFirstName.Text, txtLastName.Text) + System.Environment.NewLine;
File.AppendAllText(file.FileName, line);
您还需要将“SaveFileDialog文件”移动为类字段,而不是方法局部变量
您没有指定输出格式。我选择的是CSV。。。但是输入不能逃逸,这需要防止输入逗号弄乱输出。那部分由你决定
请注意File.Create和File.AppendAllText的使用-这两种方法使您不必在实际I/O中使用它们。您是否查看了上的Write and WriteLine方法?您可能还应该在using块中使用StreamWriter,以确保它在使用后得到处理。既然您已经知道您正在使用StreamWriter类,为什么不直接阅读它的MSDN条目呢?谢谢大家,在另一篇文章和MSDN中,我让它工作了,我会在稍后发布我的最终代码,但现在我不能,因为我没有足够的信誉点,在这里发布你的答案代码或只是在评论中做一个“谢谢”是正确的礼仪吗?
string line = string.Join(",", txtAccount.Text, txtBalance.Text, txtFirstName.Text, txtLastName.Text) + System.Environment.NewLine;
File.AppendAllText(file.FileName, line);