核心類別速查表
| 類別 | 命名空間 | 定位 | 關鍵成員 |
File | System.IO | 靜態工具類,操作實體檔案 | Copy, Create, Delete, Exists, Move, Open, ReadAllText, WriteAllText |
Directory | System.IO | 靜態工具類,操作目錄 | CreateDirectory, Delete, Exists, GetDirectories, GetFiles, Move |
Path | System.IO | 路徑字串處理 | Combine, GetFileName, GetDirectoryName, GetExtension, ChangeExtension, GetTempPath |
FileInfo | System.IO | 檔案實例資訊與操作 | Length, CreationTime, DirectoryName, Exists, Open, OpenRead, OpenWrite, CopyTo, MoveTo, Delete |
DirectoryInfo | System.IO | 目錄實例資訊與操作 | GetFiles, GetDirectories, CreateSubdirectory, Delete, MoveTo |
FileStream | System.IO | 位元組串流,支援同步/非同步、隨機存取 | Read, Write, Seek, Position, Length, Flush, Lock, Unlock |
StreamReader | System.IO | 文字讀取器(字元解碼),包裝 Stream | Read, ReadLine, ReadToEnd, CurrentEncoding, EndOfStream |
StreamWriter | System.IO | 文字寫入器(字元編碼),包裝 Stream | Write, WriteLine, Flush, AutoFlush, Encoding |
FileSystemWatcher | System.IO | 監控檔案系統變更事件 | Changed, Created, Deleted, Renamed, EnableRaisingEvents, Filter, IncludeSubdirectories |
路徑處理最佳實務
- 永遠使用
Path.Combine 組合路徑,避免手工拼接 \\ 或 /。
- 相對路徑基於
AppDomain.CurrentDomain.BaseDirectory (EXE 目錄) 或 Environment.CurrentDirectory。
- 跨平台:.NET Core 預設支援 Unix 路徑分隔符,
Path.DirectorySeparatorChar 自動適配。
FileStream 進階操作
// 開啟/建立模式
var fs = new FileStream("data.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
// 隨機存取
fs.Seek(100, SeekOrigin.Begin); // 從開頭偏移 100 位元組
fs.Seek(-50, SeekOrigin.End); // 從結尾倒數 50 位元組
fs.Seek(10, SeekOrigin.Current); // 從目前位置偏移 10
// 讀寫位元組陣列
byte[] buffer = new byte[1024];
int read = fs.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, read);
// 非同步 (高併發必備)
await fs.ReadAsync(buffer, 0, buffer.Length);
await fs.WriteAsync(buffer, 0, read);
StreamReader/Writer 文字處理範例
讀取全文
string text = File.ReadAllText("log.txt", Encoding.UTF8); // 簡便
// 或大檔案逐行
using (var sr = new StreamReader("big.log", Encoding.UTF8))
{
string line;
while ((line = sr.ReadLine()) != null) Process(line);
}
寫入文字
// 覆寫
File.WriteAllText("out.txt", "Hello", Encoding.UTF8);
// 附加
using (var sw = new StreamWriter("out.txt", true, Encoding.UTF8)) // append = true
{
sw.WriteLine("Line 1");
sw.Write("Line 2 ");
sw.Write("continued");
}
CSV 解析 (StreamReader + Split)
using (var sr = new StreamReader("data.csv"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] fields = line.Split(',');
// 若欄位含逗號/引號,請使用 TextFieldParser (Microsoft.VisualBasic.FileIO) 或 CsvHelper 套件
}
}
FileSystemWatcher 監控範例
var watcher = new FileSystemWatcher(@"C:\Inbox")
{
Filter = "*.xml",
IncludeSubdirectories = true,
EnableRaisingEvents = true
};
watcher.Created += (s, e) => Console.WriteLine($"新增: {e.FullPath}");
watcher.Changed += (s, e) => Console.WriteLine($"變更: {e.FullPath} ({e.ChangeType})");
watcher.Renamed += (s, e) => Console.WriteLine($"重命名: {e.OldFullPath} -> {e.FullPath}");
// 注意: 事件在背景執行緒觸發,UI 更新需 Invoke/Dispatcher
常見陷阱與解決方案
| 問題 | 原因 | 解決 |
| 檔案被鎖定無法存取 | 未正確 Dispose Stream/Reader/Writer | 全程使用 using 區塊確保釋放 |
| 中文亂碼 | 編碼不一致 (預設 UTF-8 vs ANSI) | 明確指定 Encoding.UTF8 或 Encoding.GetEncoding("GB2312") |
| 大檔案 OOM | ReadAllText 一次載入記憶體 | 改用 StreamReader.ReadLine 逐行或 FileStream 分塊處理 |
| 路徑過長 (>260) | Windows MAX_PATH 限制 | 啟用 Long Path (組態/登錄) 或使用 \\?\ 前綴 |
| 非同步死結 | .Result / .Wait() 造成同步阻塞 | 全程 async/await,避免同步等待 |
.NET 6+ 現代 API 亮點
File.ReadAllLinesAsync、File.WriteAllTextAsync 內建非同步。
Path.Join 多段組合、Path.GetRelativePath 計算相對路徑。
RandomAccess 類別:無需開啟 FileStream 即可隨機讀寫 (高效能)。
File.OpenHandle 取得 SafeFileHandle 進行低層級 I/O。