随手记录:C#读写txt文件

读文件:

//read text from file and show in TextArea1
FileStream fileStream = new FileStream("F:\\VisualStudioWorkspace\\WebSite2\\App_Data\\numData.txt", FileMode.Open);
StreamReader streamReader = new StreamReader(fileStream);
TextArea1.InnerText = "";
String tempString;
while ((tempString = streamReader.ReadLine()) != null) {
        TextArea1.InnerText += (tempString + "\n");
}
//close 
streamReader.Close();
fileStream.Close();

 

写文件:

string inputNum = TextBox2.Text;

//write inputNum into file
FileStream fileStream = new FileStream("F:\\VisualStudioWorkspace\\WebSite2\\App_Data\\numData.txt", FileMode.Append);
StreamWriter streamWriter = new StreamWriter(fileStream);
streamWriter.WriteLine(inputNum);
//clear buffer
streamWriter.Flush();
//close 
streamWriter.Close();
fileStream.Close();

 

 

注意FileStream打开文件时的模式FileMode,如果写文件的时候选择了Open模式,会将文件中的内容覆盖掉。

posted on 2016-07-26 14:54  ReynoldCheung  阅读(192)  评论(0编辑  收藏  举报

导航