C#讀寫TxT文件


文/嶽永鵬

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類。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM