C# StreamReader類用于從流中讀取字符串。它繼承自TextReader類,它提供Read()和ReadLine()方法從流中讀取數(shù)據(jù)。
下面來看看一個StreamReader類的簡單例子,它從文件中讀取一行數(shù)據(jù)。
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文件的內(nèi)容如下 -
This is line 1
This is line 2
This is line 3
This is line 4
執(zhí)行上面示例代碼,得到以下輸出結果 -
This is line 1
This is line 2
下面代碼演示如何使用 StreamReader 來讀取文件:myoutput.txt中的所有行內(nèi)容 -
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();
}
}
執(zhí)行上面示例代碼,得到以下輸出結果 -
This is line 1
This is line 2
This is line 3
This is line 4