標籤:style blog http color strong 檔案
文/嶽永鵬
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; }View Code
其中
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 }View Code
而在這之中,相對於讀入TxT檔案相比,在寫的時候,多用到了 FileStream類。