// 1. 開啟檔案流 (唯讀、共用讀取)
using (var fs = new FileStream("data.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
{
// 2. 配置緩衝區 (小檔案可一次讀完,大檔案分塊讀取)
byte[] buffer = new byte[fs.Length]; // 注意:大檔案不可這樣配置
// 3. 讀取
int bytesRead = fs.Read(buffer, 0, buffer.Length);
// 4. 位元組轉字串
string content = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine(content);
} // using 區塊結束自動 Dispose (關閉檔案、釋放控制代碼)
string msg = "Hello World";
byte[] data = Encoding.UTF8.GetBytes(msg);
using (var fs = new FileStream("output.txt", FileMode.Create, FileAccess.Write, FileShare.None))
{
fs.Write(data, 0, data.Length);
// fs.Flush(); // using 會自動 Flush 並關閉
}
| 方向 | 方法 | 常用編碼 |
|---|---|---|
| 字串 → 位元組 | Encoding.GetBytes(string) |
UTF8 (預設)、Unicode、Default (ANSI/系統代碼頁)、BigEndianUnicode |
| 位元組 → 字串 | Encoding.GetString(byte[]) |
同上,**讀寫必須使用相同編碼**,否則中文亂碼 |
// 寫入指定編碼
byte[] data = Encoding.GetEncoding("GB2312").GetBytes("中文測試");
// 讀取指定編碼
string text = Encoding.GetEncoding("GB2312").GetString(bytes);
Encoding.UTF8.GetPreamble() 產生 EF BB BF,標記編碼,Notepad 等編輯器依賴它識別 UTF-8。IDisposable 的類別佔用非受控資源(檔案控制代碼、網路 Socket、資料庫連線、GDI 物件),GC **不會** 自動釋放,必須手動 Dispose()。using 區塊是 try-finally 的語法糖,**保證離開區塊時呼叫 Dispose**,即使發生例外。IDisposable 物件 (純記憶體物件) 交給 GC 即可,無需釋放。// 逐行寫入 (自動處理編碼、換行)
using (var sw = new StreamWriter("log.txt", true, Encoding.UTF8)) // true = append
{
sw.WriteLine("第一行");
sw.WriteLine("第二行 {0:yyyy-MM-dd}", DateTime.Now);
sw.Write("不換行內容");
sw.Flush(); // 立即寫入磁碟
}
// 逐行讀取 (記憶體友善,適合大檔案)
using (var sr = new StreamReader("log.txt", Encoding.UTF8))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
// 或一次讀完:string all = sr.ReadToEnd();
}
public async Task ReadAllTextAsync(string path)
{
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) // true = useAsync
using (var sr = new StreamReader(fs, Encoding.UTF8))
{
return await sr.ReadToEndAsync();
}
}
public async Task WriteLinesAsync(string path, IEnumerable lines)
{
using (var sw = new StreamWriter(path, false, Encoding.UTF8, 4096, true))
{
foreach (var line in lines)
await sw.WriteLineAsync(line);
}
}
FileStream 建構式最後一個參數 useAsync=true 啟用 IOCP 非同步 I/O,釋放執行緒。StreamReader/Writer 的 Async 方法,實現真正非同步檔案操作。byte[fs.Length]:導致 LOH (Large Object Heap) 碎片化,應分塊 fs.Read(buffer, 0, buffer.Length) 迴圈讀取。Flush / Dispose:資料留在緩衝區未寫入磁碟,掉電遺失。Path.Combine、Path.GetFullPath、@"" 逐字字串避免跳脫字元錯誤。FileStream 是底層位元組流,StreamReader/Writer 是文字行導向封裝,**永遠用 using 確保釋放**,**讀寫編碼必須一致**,大檔案分塊讀寫、高併發用非同步 API。掌握這些核心,檔案操作不再出錯。