导读StreamReader是.NET框架提供的一种用于读取文本文件的流,无需手动进行文件的打开和关闭。
StreamReader的构造函数

在使用StreamReader之前,需要先创建一个StreamReader对象,

StreamReader是.NET框架提供的一种用于读取文本文件的流,无需手动进行文件的打开和关闭。

StreamReader的构造函数

streamreader(使用StreamReader读取文本文件的方法)

在使用StreamReader之前,需要先创建一个StreamReader对象,构造函数如下:

StreamReader sr = new StreamReader(string path);

其中path是文本文件的路径。如果希望指定编码格式,可以使用重载构造函数:

StreamReader sr = new StreamReader(string path, Encoding encoding);

encoding参数是一个System.Text.Encoding类型的对象,可以指定读取文件的编码格式。

StreamReader的读取方法

streamreader(使用StreamReader读取文本文件的方法)

StreamReader提供了多种读取文本文件的方法:

  1. Read():读取一个字符。
  2. ReadBlock(char[] buffer, int index, int count):从指定位置读取一定数量的字符。
  3. ReadToEnd():读取文本文件的全部内容。

StreamReader的使用示例

streamreader(使用StreamReader读取文本文件的方法)

下面是一个示例,演示如何使用StreamReader读取文本文件,并逐行输出文件内容:

StreamReader sr = new StreamReader(\"test.txt\", Encoding.UTF8);

string line;

while ((line = sr.ReadLine()) != null)

{

  Console.WriteLine(line);

}

上述代码中,通过ReadLine()方法一行一行地读取文本文件,当读取到文件末尾时返回null,循环结束。