文/嶽永鵬
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; }
其中
1 using (StreamReader sr = new StreamReader(openFile.FileName, Encoding.Default)) 2 { 3 int lineCount = 0; 4 while (sr.Peek() > 0) 5 { 6 lineCount++; 7 string temp = sr.ReadLine(); 8 txt.Add(temp); 9 } 10 }
StreamReader 是以流的方式逐行將TxT內容保存到List<string> txt中。
其次,對TxT文件的寫入操作,也是將數組List<string> 中的每個元素逐行寫入到TxT中,並保存為.txt文件。且看代碼:

1 SaveFileDialog sf = new SaveFileDialog(); 2 sf.Title = "Save text Files"; 3 sf.DefaultExt = "txt"; 4 sf.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; 5 sf.FilterIndex = 1; 6 sf.RestoreDirectory = true; 7 if ((bool)sf.ShowDialog()) 8 { 9 using (FileStream fs = new FileStream(sf.FileName, FileMode.Create)) 10 { 11 using (StreamWriter sw = new StreamWriter(fs, Encoding.Default)) 12 { 13 for (int i = 0; i < txt.Count; i++) 14 { 15 sw.WriteLine(txt[i]); 16 } 17 } 18 } 19 20 }
而在這之中,相對於讀入TxT文件相比,在寫的時候,多用到了 FileStream類。