using System.IO;
bool exists = File.Exists(Application.StartupPath + @"\AlarmSet.txt");
最簡潔、語意明確、效能佳。回傳 true 表示檔案存在且為檔案(非目錄)。
var info = new DirectoryInfo(Application.StartupPath + @"\AlarmSet.txt");
bool exists = info.Exists;
注意:DirectoryInfo 針對**目錄**,若路徑為檔案則永遠回傳 false。此用法**錯誤**。正確用法應為 FileInfo:
var info = new FileInfo(path);
bool exists = info.Exists;
File.Create(path); // 若不存在會建立,存在則覆寫/拋出例外
此法**副作用嚴重**:會實際建立/截斷檔案,非單純判斷。僅在「不存在則建立」的原子操作中適用。
| 方法 | 正確性 | 副作用 | 適用場景 |
|---|---|---|---|
| File.Exists | ✓ | 無 | 純判斷存在性 |
| FileInfo.Exists | ✓ | 無 | 需後續操作檔案屬性(長度、時間等) |
| DirectoryInfo.Exists | ✗ (針對檔案) | 無 | 判斷目錄存在 |
| File.Create | ✗ (非判斷用途) | 建立/覆寫檔案 | 確保檔案存在並取得 FileStream |
判斷檔案存在請直接使用 File.Exists 或 new FileInfo(path).Exists。切勿使用 DirectoryInfo 檢查檔案,也不要用 File.Create 做判斷。