StreamReader类

StreamReader类用于从文件中读取数据,该类是一个通用类,可用于任何流,构造方法和StreamWrite类格式一样的。

创建方式有两种:

  1.先创建Filestream类在创建StreamReader类

          FIlestream a=new FileStream(string path,FileMode mode);

     StreamReader sd=new StreamReader(a);

  2.直接创建StreamReader类

     StreamReader sd=new StreamReader(string path);

StreamReader 类以一种特定的编码输入字符,而StreamReader类可读取标准的文本文件的各行信息,StreamReader的

默认编码为UTF-8,UTF-8可以正确的处理Unicode字符并在操作系统的本地化版本上提供一直的结果。

StreamReader类的常用方法

Close      关闭当前StreamReader对象和基础流

Dispose     释放使用的所有资源

Peek         返回下一个可用的字符

Read        读取输入流中的下一个字符或下组字符

ReadLine      从数据流中读取一行数据,并作为字符串返回

实例:  找到Host文件 并读取到屏幕上

    class Program
    {
        static void Main(string[] args)
        {
            string path = @"C:WindowsSystem32driversetchosts";//文件路径
            string read="";//定义字符串read接收读取流
            if (File.Exists(path))
            {
                //using(){} 自动帮助我们释放流所占用的空间
                //()创建过程 {}读取或写入过程  均不能加分号;
                using(StreamReader sd = new StreamReader(path))
                {
                    read = sd.ReadLine();
                    while (read!=null)
                    {
                        Console.WriteLine(read);
                        read = sd.ReadLine();
                    }
                }
                
               
            }
            else
            {
                Console.WriteLine("没有找到要读取的文件");
            }
            Console.Read();
        }
    }

  

原文地址:https://www.cnblogs.com/xiaowie/p/8861784.html