文/嶽永鹏
WPF 中读取和写入TxT 是经常性的操作,本篇将从详细演示WPF如何读取和写入TxT文件。
首先,TxT文件希望逐行读取,并将每行读取到的数据作为一个数组的一个元素,因此需要引入List<string> 数据类型。且看代码:
public List<string> OpenTxt(TextBox tbx) { List<string> txt = new List<string>(); OpenFileDialog openFile = new OpenFileDialog(); openFile.Filter = "文本文件(*.txt)|*.txt|(*.rtf)|*.rtf"; if (openFile.ShowDialog() == true) { tbx.Text = ""; using (StreamReader sr = new StreamReader(openFile.FileName, Encoding.Default)) { int lineCount = 0; while (sr.Peek() > 0) { lineCount++; string temp = sr.ReadLine(); txt.Add(temp); } } } return txt; }