命名空間
using System.IO;
常用屬性
| 屬性 | 型別 | 說明 |
| CanRead | bool | 流是否支援讀取 |
| CanWrite | bool | 流是否支援寫入 |
| CanSeek | bool | 流是否支援定位 (檔案通常為 true,網路流通常為 false) |
| Length | long | 流長度 (位元組),需 CanSeek=true |
| Position | long | 當前指標位置,可獲取/設定,需 CanSeek=true |
核心方法
| 方法 | 簽名 | 說明 |
| Read | int Read(byte[] buffer, int offset, int count) | 讀取最多 count 位元組到 buffer,返回實際讀取數;0 表示 EOF |
| ReadAsync | Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken ct) | 非同步讀取,**建議優先使用** |
| Write | void Write(byte[] buffer, int offset, int count) | 寫入 buffer 指定範圍 |
| WriteAsync | Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken ct) | 非同步寫入 |
| Seek | long Seek(long offset, SeekOrigin origin) | 移動指標:Begin/Current/End |
| Flush | void Flush() | 清空緩衝區至作業系統 (不保證寫入實體磁碟) |
| FlushAsync | Task FlushAsync(CancellationToken ct) | 非同步刷新 |
| Close | void Close() | 關閉流、釋放控制碼 (等同 Dispose()) |
檔案開啟模式枚舉 (FileMode)
| 枚舉值 | 行為 | 典型場景 |
| CreateNew | 新建,存在則拋異常 | 獨佔建立,防覆蓋 |
| Create | 新建,存在則**截斷覆蓋** | 寫入新內容 (最常用) |
| Open | 開啟現有,不存在拋異常 | 讀取/修改既有檔案 |
| OpenOrCreate | 開啟現有,不存在則新建 | 讀寫通用、不想處理不存在例外 |
| Append | 開啟現有並定位至末尾,不存在則新建,**只能搭配 FileAccess.Write** | 日誌追加、斷點續傳 |
| Truncate | 開啟現有並**清空內容** (長度歸零) | 重寫整個檔案 |
檔案存取權限 (FileAccess)
Read、Write、ReadWrite
- 必須與 FileMode 邏輯相容 (如 Append 僅能搭配 Write)。
檔案共享模式 (FileShare) — 關鍵併發控制
| 枚舉值 | 允許其他進程 | 典型用途 |
| None | 無 (獨佔) | 獨佔寫入、安裝程式替換檔案 |
| Read | 讀取 | 多進程同時讀日誌/設定檔 |
| Write | 寫入 | 極少用,易造成資料損毀 |
| ReadWrite | 讀寫 | 高併發日誌、資料庫檔案 (需應用層協調) |
| Delete | 刪除檔案 | 允許其他進程刪除已開啟檔案 |
| Inheritable | 子進程繼承控制碼 | 進程間傳遞檔案控制碼 |
建構子多載 (常用三種)
// 1. 最簡單
new FileStream(path, FileMode.Create)
// 2. 指定存取權限
new FileStream(path, FileMode.Create, FileAccess.Write)
// 3. 完整控制
new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true)
建議: 高效能 I/O 啟用 useAsync: true (Windows 使用 IOCP),緩衝區 4K-64K。
File 靜態工廠方法 (更簡潔)
| 方法 | 等價 FileStream 建構 | 適用場景 |
File.OpenRead(path) | new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read) | 唯讀共享 |
File.OpenWrite(path) | new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.None) | 追加寫入 |
File.Open(path, mode) | 自訂模式,預設 ReadWrite + Read 共享 | 需精確控制時 |
標準讀寫模板 (using 確保釋放)
讀取文字檔
using (var fs = File.OpenRead(path))
using (var sr = new StreamReader(fs, Encoding.UTF8)) {
string content = await sr.ReadToEndAsync();
// 處理內容
}
寫入文字檔
using (var fs = File.OpenWrite(path))
using (var sw = new StreamWriter(fs, new UTF8Encoding(false))) { // 無 BOM
await sw.WriteAsync(content);
}
二進位複製 (高效能)
using (var src = File.OpenRead(srcPath))
using (var dst = File.OpenWrite(dstPath)) {
await src.CopyToAsync(dst); // 內部使用 4096 緩衝區
}
常見坑點
- 未使用 using/try-finally → 檔案鎖定、資源洩漏。
- Append 模式搭配 ReadWrite → 異常。
- Position 設定超出 Length → 寫入會擴展檔案 (中間補 0),讀取拋異常。
- Flush ≠ 寫入磁碟:需
FileOptions.WriteThrough 或 Flush() + Handle.FlushFileBuffers() (P/Invoke) 保證持久化。
- 大檔案一次性 ReadAllBytes → LOH 壓力、OOM 風險,改用流式分塊處理。
結語
FileStream 是 .NET 底層 I/O 基石。熟記 FileMode/FileAccess/FileShare 三維組合、優先使用 Async 版本**、善用 File 工廠方法與 StreamReader/Writer 封裝,能寫出正確、高效、併發安全的檔案操作代碼。