C# 文本檔的讀寫
StreamReader 和 StreamWriter 類用於文本檔的數據讀寫。這些類從抽象基類 Stream 繼承,Stream 支持檔流的位元組讀寫。
StreamReader 類
StreamReader 類繼承自抽象基類 TextReader,表示閱讀器讀取一系列字元。
下表列出了 StreamReader 類中一些常用的方法:
序號 | 方法 & 描述 |
---|---|
1 | public override void Close() 關閉 StreamReader 對象和基礎流,並釋放任何與讀者相關的系統資源。 |
2 | public override int Peek() 返回下一個可用的字元,但不使用它。 |
3 | public override int Read() 從輸入流中讀取下一個字元,並把字元位置往前移一個字元。 |
如需查看完整的方法列表,請訪問微軟的 C# 文檔。
實例
下麵的實例演示了讀取名為 Jamaica.txt 的檔。檔如下:
Down the way where the nights are gay And the sun shines daily on the mountain top I took a trip on a sailing ship And when I reached Jamaica I made a stop
using System; using System.IO; namespace FileApplication { class Program { static void Main(string[] args) { try { // 創建一個 StreamReader 的實例來讀取檔 // using 語句也能關閉 StreamReader using (StreamReader sr = new StreamReader("c:/jamaica.txt")) { string line; // 從檔讀取並顯示行,直到檔的末尾 while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } } catch (Exception e) { // 向用戶顯示出錯消息 Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } Console.ReadKey(); } } }
當您編譯和執行上面的程式時,它會顯示檔的內容。
StreamWriter 類
StreamWriter 類繼承自抽象類 TextWriter,表示編寫器寫入一系列字元。
下表列出了 StreamWriter 類中一些常用的方法:
序號 | 方法 & 描述 |
---|---|
1 | public override void Close() 關閉當前的 StreamWriter 對象和基礎流。 |
2 | public override void Flush() 清理當前編寫器的所有緩衝區,使得所有緩衝數據寫入基礎流。 |
3 | public virtual void Write(bool value) 把一個布爾值的文本表示形式寫入到文本字串或流。(繼承自 TextWriter。) |
4 | public override void Write(
char value
)
把一個字元寫入到流。 |
5 | public virtual void Write(
decimal value
)
把一個十進位值的文本表示形式寫入到文本字串或流。 |
6 | public virtual void Write(
double value
)
把一個 8 位元組浮點值的文本表示形式寫入到文本字串或流。 |
7 | public virtual void Write(
int value
)
把一個 4 位元組有符號整數的文本表示形式寫入到文本字串或流。 |
8 | public override void Write(
string value
)
把一個字串寫入到流。 |
9 | public virtual void WriteLine() 把行結束符寫入到文本字串或流。 |
如需查看完整的方法列表,請訪問微軟的 C# 文檔。
實例
下麵的實例演示了使用 StreamWriter 類向檔寫入文本數據:
using System; using System.IO; namespace FileApplication { class Program { static void Main(string[] args) { string[] names = new string[] {"Zara Ali", "Nuha Ali"}; using (StreamWriter sw = new StreamWriter("names.txt")) { foreach (string s in names) { sw.WriteLine(s); } } // 從檔中讀取並顯示每行 string line = ""; using (StreamReader sr = new StreamReader("names.txt")) { while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } Console.ReadKey(); } } }
當上面的代碼被編譯和執行時,它會產生下列結果:
Zara Ali Nuha Ali