StreamReader
StreamReader繼承了抽象類別TextReader,
先準備一個名為StreamReader.txt的Sample檔,內容為
abc123
abc223
以下程式碼為四種結果一樣的讀取方式
C#
using System;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
//StreamReader讀取方式一
StreamReader sr = new StreamReader("d:\\StreamReader.txt", Encoding.Default);
Console.WriteLine(sr.ReadToEnd());
sr.Close();
Console.ReadLine();
//StreamReader讀取方式二
FileInfo f = new FileInfo("d:\\StreamReader.txt");
StreamReader sr2 = f.OpenText();
Console.WriteLine(sr2.ReadToEnd());
sr2.Close();
Console.ReadLine();
//StreamReader讀取方式三,一次讀取一行
FileInfo f2 = new FileInfo("d:\\StreamReader.txt");
StreamReader sr3 = f2.OpenText();
//若傳回-1則表示沒有字元可以讀取
while (sr3.Peek() >= 0)
{
Console.WriteLine(sr3.ReadLine());
}
sr3.Close();
Console.ReadLine();
//StreamReader讀取方式四,一次讀取一字元
FileInfo f3 = new FileInfo("d:\\StreamReader.txt");
StreamReader sr4 = f3.OpenText();
//若傳回-1則表示沒有字元可以讀取
while (sr4.Peek() >= 0)
{
Console.Write(char.ConvertFromUtf32((int)sr4.Read()));
}
sr4.Close();
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
}
}
}
}
每一種方式技術說明為:
(1)、使用StreamReader並藉由ReadToEnd讀完整個文字檔
(2)、由FileInfo.OpenText()產生StreamReader物件並藉由ReadToEnd讀完整個文字檔
(3)、由FileInfo.OpenText()產生StreamReader物件並藉由Peek與ReadLine讀完整個文字檔
(4)、由FileInfo.OpenText()產生StreamReader物件並藉由Peek與Read讀完整個文字檔
我有一個想法,有時候ReadToEnd來不及讀完,則是否要使用streamReader.Read(buffer, 0, buffer.Length);
來放慢速度讀取?這想法有待試驗。
以下為VB.NET版本僅供參考
Imports system.IO Imports system.Text Module Module1 Sub Main() 'StreamReader讀取方式一 Dim sr As New StreamReader("c:\StreamReader.txt", Encoding.Default) Console.WriteLine(sr.ReadToEnd()) sr.Close() Console.ReadLine() 'StreamReader讀取方式二 Dim f As New FileInfo("c:\StreamReader.txt") Dim sr2 As StreamReader = f.OpenText Console.WriteLine(sr2.ReadToEnd) sr2.Close() Console.ReadLine() '一次讀取一行 Dim f2 As New FileInfo("c:\StreamReader.txt") Dim sr3 As StreamReader = f2.OpenText Do While sr3.Peek >= 0 '若傳回-1則表示沒有字元可以讀取 Console.WriteLine(sr3.ReadLine) Loop sr3.Close() Console.ReadLine() '一次讀取一字元 Dim f3 As New FileInfo("c:\StreamReader.txt") Dim sr4 As StreamReader = f3.OpenText Do While sr4.Peek >= 0 '若傳回-1則表示沒有字元可以讀取 Console.Write(ChrW(sr4.Read)) Loop sr4.Close() Console.ReadLine() End Sub End Module
參考資料: