zoukankan      html  css  js  c++  java
  • c# txt文件的读取和写入

      我们在工程实践中经常要处理传感器采集的数据,有时候要把这些数据记录下来,有时候也需要把记录下来的数据读取到项目中。接下来我们用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();
    
            }
        }
    }
    

      

  • 相关阅读:
    禁止logback输出状态信息
    Idea导出可运行Jar包
    K均值算法
    [转]香农信息论与毒药称球问题
    ajax跨域请求
    Python函数的静态变量
    学倦乱语
    [转]被当做狗和鸡来驱赶的百姓
    numpy文件读写的三对函数
    认真把事办砸是一种能力
  • 原文地址:https://www.cnblogs.com/fuhang/p/7812970.html
Copyright © 2011-2022 走看看