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