C# StreamReader类

C# StreamReader类用于从流中读取字符串。它继承自TextReader类,它提供Read()ReadLine()方法从流中读取数据。

C# StreamReader示例:读取一行

下面来看看一个StreamReader类的简单例子,它从文件中读取一行数据。

using System;
using System.IO;
public class StreamReaderExample
{
    public static void Main(string[] args)
    {
        FileStream f = new FileStream("e:\\myoutput.txt", FileMode.OpenOrCreate);
        StreamReader s = new StreamReader(f);

        string line = s.ReadLine();
        Console.WriteLine(line);
        string line2 = s.ReadLine();
        Console.WriteLine(line2);
        s.Close();
        f.Close();
    }
}

假设e:\myoutput.txt文件的内容如下 -

This is line 1
This is line 2
This is line 3
This is line 4

执行上面示例代码,得到以下输出结果 -

This is line 1
This is line 2

C# StreamReader示例:读取所有行

下面代码演示如何使用 StreamReader 来读取文件:myoutput.txt中的所有行内容 -

using System;
using System.IO;
public class StreamReaderExample
{
    public static void Main(string[] args)
    {
        FileStream f = new FileStream("e:\\myoutput.txt", FileMode.OpenOrCreate);
        StreamReader s = new StreamReader(f);

        string line = "";
        while ((line = s.ReadLine()) != null)
        {
            Console.WriteLine(line);
        }
        s.Close();
        f.Close();
    }
}

执行上面示例代码,得到以下输出结果 -

This is line 1
This is line 2
This is line 3
This is line 4

上一篇: C# FileStream类 下一篇: C# TextWriter类