| 類別 | 特性 | 適用場景 |
|---|---|---|
| File | 靜態方法 | 單次檔案建立/複製/移動/刪除/開啟串流 |
| FileInfo | 實例方法 | 對同一檔案多次操作、取得屬性資訊 |
| Directory | 靜態方法 | 單次目錄操作 |
| DirectoryInfo | 實例方法 | 列舉子目錄/檔案、多次操作同目錄 |
| DriveInfo | 實例 (靜態取得) | 取得磁碟機資訊 (類型、容量、剩餘空間) |
| FileSystemWatcher | 事件導向 | 即時監控檔案/目錄變更 |
| Path | 靜態方法 | 路徑字串操作 (合併、取副檔名、取隨機檔名…) |
foreach (var drive in DriveInfo.GetDrives()) {
if (drive.IsReady) {
Console.WriteLine($"類型:{drive.DriveType} 卷標:{drive.VolumeLabel} " +
$"{drive.Name} 總計:{drive.TotalSize/1e9:F1}GB 剩餘:{drive.TotalFreeSpace/1e9:F1}GB");
} else {
Console.WriteLine($"{drive.DriveType} 未就緒 (可能無媒體)");
}
}
⚠ 必須先檢查 IsReady,否則存取 TotalSize 等屬性會擲出例外。
var watcher = new FileSystemWatcher(@"D:\watch", "*.*");
watcher.Changed += (s, e) => Console.WriteLine($"Changed: {e.FullPath}");
watcher.Created += (s, e) => Console.WriteLine($"Created: {e.FullPath}");
watcher.Deleted += (s, e) => Console.WriteLine($"Deleted: {e.FullPath}");
watcher.Error += (s, e) => Console.WriteLine($"Error: {e.GetException()}");
watcher.EnableRaisingEvents = true; // 必須設為 true 才啟動
Console.WriteLine("監控中... 按任意鍵結束"); Console.ReadKey();
常用過濾:watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
Path.GetDirectoryName(@"d:\abc") // "d:\"
Path.GetDirectoryName(@"d:\abc\") // "d:\abc" (尾斜線影響結果)
Path.GetFileNameWithoutExtension(@"d:\abc.txt") // "abc"
Path.GetRandomFileName() // "abc123.tmp" (加密隨機)
Path.Combine(@"d:\folder", "file.txt") // "d:\folder\file.txt"
Path.GetInvalidPathChars() // 陣列:不可用於路徑的字元
Path.GetInvalidFileNameChars() // 陣列:不可用於檔名的字元
上述類別底層呼叫 Windows API,**僅限 Windows 環境**。.NET Core / .NET 5+ 跨平台專案請改用 System.IO.Abstractions 或直接使用 File/Directory (已支援 Linux/macOS),但 DriveInfo、FileSystemWatcher 行為在非 Windows 平台可能不同。