WPF 讀寫TxT檔案

來源:互聯網
上載者:User

標籤: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類。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.