`System.IO` 命名空間提供檔案/目錄操作核心類別。本文整理最常用、最安全的模式,強調 `using` 區塊確保資源釋放、編碼指定、大檔案串流處理。
using System.IO;
using System.Text; // Encoding
string dir = @"C:\Data\Logs";
// 建立目錄 (含父目錄,存在不報錯)
Directory.CreateDirectory(dir);
// 判斷存在
if (Directory.Exists(dir)) { ... }
// 取得子目錄
string[] subDirs = Directory.GetDirectories(dir, "*", SearchOption.TopDirectoryOnly);
// 取得檔案
string[] files = Directory.GetFiles(dir, "*.log", SearchOption.AllDirectories);
// 刪除目錄及所有內容 (小心!)
Directory.Delete(dir, true);
// 移動/重命名目錄
Directory.Move(@"C:\Old", @"C:\New");
// 覆寫 (預設 UTF-8 無 BOM)
File.WriteAllText(path, content, Encoding.UTF8);
// 附加
File.AppendAllText(path, newLine + Environment.NewLine, Encoding.UTF8);
// 寫入多行
File.WriteAllLines(path, lines, Encoding.UTF8);
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096))
using (var writer = new StreamWriter(fs, Encoding.UTF8))
{
foreach (var line in hugeDataGenerator())
{
writer.WriteLine(line);
}
// writer.Flush(); // using 會自動 Flush/Dispose
}
string allText = File.ReadAllText(path, Encoding.UTF8);
string[] lines = File.ReadAllLines(path, Encoding.UTF8);
// 模式 1: File.ReadLines (延遲執行、逐行列舉)
foreach (string line in File.ReadLines(path, Encoding.UTF8))
{
ProcessLine(line);
}
// 模式 2: StreamReader (完整控制)
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096))
using (var reader = new StreamReader(fs, Encoding.UTF8, detectEncodingFromByteOrderMarks: true))
{
string line;
while ((line = reader.ReadLine()) != null)
{
ProcessLine(line);
}
}
// 複製 (覆寫目標)
File.Copy(source, dest, overwrite: true);
// 移動 (跨磁碟會複製後刪除來源)
File.Move(source, dest);
// 大檔案複製進度回報
public static void CopyWithProgress(string src, string dst, IProgress progress)
{
using (var s = File.OpenRead(src))
using (var d = File.Create(dst))
{
byte[] buffer = new byte[81920]; // 80KB
long total = s.Length, copied = 0;
int read;
while ((read = s.Read(buffer, 0, buffer.Length)) > 0)
{
d.Write(buffer, 0, read);
copied += read;
progress.Report((double)copied / total);
}
}
}
Path.Combine(dir, "sub", "file.txt") // 安全合併
Path.GetFileName(path) // "file.txt"
Path.GetDirectoryName(path) // 目錄路徑
Path.GetExtension(path) // ".txt"
Path.ChangeExtension(path, ".bak") // 變更副檔名
Path.GetFullPath(relativePath) // 轉絕對路徑
Path.GetTempFileName() // 產生唯一暫存檔
Path.GetRandomFileName() // 產生隨機檔名 (無副檔名)
| 例外 | 常見原因 | 處理 |
|---|---|---|
| DirectoryNotFoundException | 路徑錯誤、磁碟機不存在 | 檢查路徑、建立目錄 |
| FileNotFoundException | 檔案不存在 | 檢查 Exist、提供預設值 |
| UnauthorizedAccessException | 權限不足、檔案被鎖定 | 檢查 ACL、重試、記錄日誌 |
| IOException | 磁碟滿、網路中斷、檔案被佔用 | 重試機制、釋放佔用程序 |
| PathTooLongException | 路徑超過 260 字元 | 啟用 Long Path (Windows 10 1607+ / .NET Core 2.0+)、縮短路徑 |