在C中保存数据到文本文档
在一些没有数据库支持的小型应用程序中,将数据保存到文本文档是首选的方法。本篇文章将分享我在C编程中将数据保存到文本文档的经验,希望能对您有所帮助。 添加相关控件 在Visual Studio中,首
在一些没有数据库支持的小型应用程序中,将数据保存到文本文档是首选的方法。本篇文章将分享我在C编程中将数据保存到文本文档的经验,希望能对您有所帮助。
添加相关控件
在Visual Studio中,首先需要添加用于保存数据的相关控件(本文的目的是将值1、值2、值3、值4保存到文本中)。
编写保存数据的文本文档创建代码
以下是创建文本文档的代码:
private void newFile()
{
if (!File.Exists("Vista" dateTime ".txt"))
{
FileStream fs1 new FileStream("Vista" dateTime ".txt", , FileAccess.Write); //创建写入文件
StreamWriter sw new StreamWriter(fs1);
();
}
else
{
FileStream fs new FileStream("Vista" dateTime ".txt", , FileAccess.Write);
();
}
}
调用创建文本文档的方法
在Form1_Load事件中调用newFile()方法:
private void Form1_Load(object sender, EventArgs e)
{
label4.Text "当前时间:" ("yyyy/MM/dd HH:mm:ss");
label3.Text "等待刷入条码......";
newFile();
}
编写变量写入文本的代码
以下是将变量写入文本的代码:
private void sw()
{
string sn1 this.textBox1.Text;
string sn2 this.textBox2.Text;
string str1 ;
string str2 ;
StreamWriter sw new StreamWriter( "Vista" dateTime ".txt", true);
sw.WriteLine(sn1 " " sn2 " " str1 " " str2);
();
}
在指定的事件中调用文件写入代码方法
在textBox2_KeyDown事件中调用sw()方法:
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
string CSN ();
string BSN ();
if (( Keys.Enter) (CSN ! "") (CSN BSN))
{
label3.Text "条码检查OK!";
[0].BackColor ;
sw();
();
();
}
else if(( Keys.Enter) (CSN ! BSN))
{
label3.Text "条码检查NG!";
[0].BackColor ;
sw();
}
}
运行测试后,成功将计划内的变量保存到指定的文本文档中。