- C# 基礎教程
- C# - 首頁
- C# - 概述
- C# - 環境
- C# - 程式結構
- C# - 基本語法
- C# - 資料型別
- C# - 型別轉換
- C# - 變數
- C# - 常量
- C# - 運算子
- C# - 決策制定
- C# - 迴圈
- C# - 封裝
- C# - 方法
- C# - 可空型別
- C# - 陣列
- C# - 字串
- C# - 結構體
- C# - 列舉
- C# - 類
- C# - 繼承
- C# - 多型
- C# - 運算子過載
- C# - 介面
- C# - 名稱空間
- C# - 預處理器指令
- C# - 正則表示式
- C# - 異常處理
- C# - 檔案 I/O
C# - 讀寫文字檔案
StreamReader 和 StreamWriter 類用於讀寫文字檔案中的資料。這些類繼承自抽象基類 Stream,該基類支援將位元組讀寫到檔案流中。
StreamReader 類
StreamReader 類也繼承自抽象基類 TextReader,該基類表示用於讀取一系列字元的讀取器。下表描述了 StreamReader 類的一些常用方法:
| 序號 | 方法和描述 |
|---|---|
| 1 | public override void Close() 它關閉 StreamReader 物件和底層流,並釋放與讀取器關聯的任何系統資源。 |
| 2 | public override int Peek() 返回下一個可用字元,但不讀取它。 |
| 3 | public override int Read() 從輸入流讀取下一個字元,並將字元位置前進一位。 |
示例
以下示例演示如何讀取名為 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 {
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("c:/jamaica.txt")) {
string line;
// Read and display lines from the file until
// the end of the file is reached.
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
}
} catch (Exception e) {
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
猜猜編譯並執行程式後它會顯示什麼!
StreamWriter 類
StreamWriter 類繼承自抽象類 TextWriter,該類表示一個寫入器,可以寫入一系列字元。
下表描述了此類最常用的方法:
| 序號 | 方法和描述 |
|---|---|
| 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() 將行終止符寫入文字字串或流。 |
有關方法的完整列表,請訪問 Microsoft 的 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);
}
}
// Read and show each line from the file.
string line = "";
using (StreamReader sr = new StreamReader("names.txt")) {
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
}
Console.ReadKey();
}
}
}
編譯並執行上述程式碼後,將產生以下結果:
Zara Ali Nuha Ali