在C中保存數(shù)據(jù)到文本文檔
在一些沒有數(shù)據(jù)庫支持的小型應(yīng)用程序中,將數(shù)據(jù)保存到文本文檔是首選的方法。本篇文章將分享我在C編程中將數(shù)據(jù)保存到文本文檔的經(jīng)驗(yàn),希望能對您有所幫助。 添加相關(guān)控件 在Visual Studio中,首
在一些沒有數(shù)據(jù)庫支持的小型應(yīng)用程序中,將數(shù)據(jù)保存到文本文檔是首選的方法。本篇文章將分享我在C編程中將數(shù)據(jù)保存到文本文檔的經(jīng)驗(yàn),希望能對您有所幫助。
添加相關(guān)控件
在Visual Studio中,首先需要添加用于保存數(shù)據(jù)的相關(guān)控件(本文的目的是將值1、值2、值3、值4保存到文本中)。
編寫保存數(shù)據(jù)的文本文檔創(chuàng)建代碼
以下是創(chuàng)建文本文檔的代碼:
private void newFile()
{
if (!File.Exists("Vista" dateTime ".txt"))
{
FileStream fs1 new FileStream("Vista" dateTime ".txt", , FileAccess.Write); //創(chuàng)建寫入文件
StreamWriter sw new StreamWriter(fs1);
();
}
else
{
FileStream fs new FileStream("Vista" dateTime ".txt", , FileAccess.Write);
();
}
}
調(diào)用創(chuàng)建文本文檔的方法
在Form1_Load事件中調(diào)用newFile()方法:
private void Form1_Load(object sender, EventArgs e)
{
label4.Text "當(dāng)前時(shí)間:" ("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);
();
}
在指定的事件中調(diào)用文件寫入代碼方法
在textBox2_KeyDown事件中調(diào)用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();
}
}
運(yùn)行測試后,成功將計(jì)劃內(nèi)的變量保存到指定的文本文檔中。