zoukankan      html  css  js  c++  java
  • 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类。

  • 相关阅读:
    4 Python+Selenium的元素定位方法(link/partial link)
    3 Python+Selenium的元素定位方法(id、class name、name、tag name)
    2 Selenium3.0+Python3.6环境搭建
    1 Selenium打开浏览器
    目录处理文件&链接命令
    DOS批处理命令-@命令
    DOS批处理命令-echo
    吐槽一二三
    编码神器之sublime(插件安装)
    两天来学习C的感受
  • 原文地址:https://www.cnblogs.com/YUEYongpeng/p/3842181.html
Copyright © 2011-2022 走看看