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