我们在工程实践中经常要处理传感器采集的数据,有时候要把这些数据记录下来,有时候也需要把记录下来的数据读取到项目中。接下来我们用C#演示如何对txt文件进行读写操作。我们要用到StreamReader 和 StreamWriter 类,用于文本文件的数据读写。这些类从抽象基类 Stream 继承,Stream 支持文件流的字节读写。过程如下:

  (1)我们新建一个C#控制平台项目,引用System.Io;

  (2)定义StreamReader对象,并将要读取文本的路径作为对象的参数;

  (3)使用readline方法读取文本中的内容,readline是一行一行的读取。

  (4)将读取的内容保存到列表中。

  (5)关闭StreamReader对象。

  文件的写入和文件的读取类似。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace writehandread
{
    class Program
    {
        static void Main(string[] args)
        {
            //将ys.txt中的内容读取到列表data中
            List<string> data = new List<string>();
            StreamReader sr = new StreamReader("D://test.txt");
            while (sr.ReadLine ()!=null  )
            {               
                data.Add(sr.ReadLine());
                
            }
            sr.Close();

            //将data中的内容写入test.txt中
            StreamWriter sw = new StreamWriter("D://test1.txt");
            for (int i=0 ;i<data .Count ;i++)
            {
                sw.WriteLine(data[i]);
            }
            sw.Flush();
            sw.Close();

        }
    }
}

  

posted on 2017-11-10 09:20  未完代码  阅读(2010)  评论(0编辑  收藏  举报