文/嶽永鹏

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

相关文章:

  • 2021-11-11
  • 2021-09-09
  • 2021-09-17
  • 2021-11-11
  • 2021-09-13
  • 2021-09-15
猜你喜欢
  • 2021-07-01
  • 2022-12-23
  • 2022-12-23
  • 2022-01-28
  • 2022-12-23
相关资源
相似解决方案