.NET 提供豐富的讀寫 API,針對不同資料性質選擇正確模式,事半功倍。
File.OpenText(path)、File.CreateText(path)
using var sr = File.OpenText(@"C:\data\log.txt");
while (sr.Peek() >= 0) {
string line = sr.ReadLine();
Console.WriteLine(line);
}
using var sw = File.CreateText(@"C:\data\output.txt");
sw.WriteLine("Web Address:");
sw.WriteLine("https://example.com");
sw.WriteLine("https://github.com");
ReadInt32/Write、ReadDouble/Write、ReadString/Write、ReadBytes/Write
struct Record {
public string Name;
public ushort Age;
public string Phone;
public string Address;
}
class PhoneBook {
private readonly string _path;
public PhoneBook(string path) => _path = path;
public void Add() {
using var fs = new FileStream(_path, FileMode.OpenOrCreate, FileAccess.Write);
using var bw = new BinaryWriter(fs);
bw.BaseStream.Seek(0, SeekOrigin.End);
Console.Write("姓名:"); var name = Console.ReadLine();
Console.Write("年齡:"); ushort age = ushort.Parse(Console.ReadLine());
Console.Write("電話:"); var phone = Console.ReadLine();
Console.Write("地址:"); var addr = Console.ReadLine();
bw.Write(name);
bw.Write(age);
bw.Write(phone);
bw.Write(addr);
}
public void List() {
using var fs = new FileStream(_path, FileMode.Open, FileAccess.Read);
using var br = new BinaryReader(fs);
Console.WriteLine($"{"姓名",-10}{"年齡",-6}{"電話",-15}{"地址"}");
while (fs.Position < fs.Length) {
try {
var r = new Record {
Name = br.ReadString(),
Age = br.ReadUInt16(),
Phone = br.ReadString(),
Address = br.ReadString()
};
Console.WriteLine($"{r.Name,-10}{r.Age,-6}{r.Phone,-15}{r.Address}");
} catch (EndOfStreamException) { break; }
}
}
public void Erase() {
File.WriteAllBytes(_path, Array.Empty());
Console.WriteLine("通訊錄已清空");
}
}
// 選單驅動
class Program {
static void Main() {
var pb = new PhoneBook(@"C:\data\phonebook.dat");
while (true) {
Console.WriteLine("1:列表 2:新增 3:清空 0:退出");
switch (Console.ReadLine()) {
case "1": pb.List(); break;
case "2": pb.Add(); break;
case "3": pb.Erase(); break;
case "0": return;
}
}
}
}
// 複合格式:{索引,對齊寬度:格式} 負寬度=靠左
Console.WriteLine($"{r.Name,-10}{r.Age,-6}{r.Phone,-15}{r.Address}");
// 等價於
Console.WriteLine("{0,-10}{1,-6}{2,-15}{3}", r.Name, r.Age, r.Phone, r.Address);
| 場景 | 推薦類別 | 關鍵理由 |
|---|---|---|
| 文字日誌/設定 | StreamReader/Writer | 編碼自動、行導向、人類可讀 |
| 高效序列化 | BinaryReader/Writer | 零解析、強型別、體積小 |
| 大檔案逐行處理 | File.ReadLines | 延遲串流、記憶體恆定 |
| 簡單全文本讀寫 | File.ReadAllText/WriteAllText | 一行代碼、小檔案適用 |
| 結構化資料 | JsonSerializer / XmlSerializer | 標準化、跨平台、Schema 驗證 |
掌握模式選擇與 API 組合,是高效處理檔案資料的關鍵。