快速參考
| 判斷對象 |
命名空間 |
方法 |
回傳值 |
| 目錄 |
System.IO |
Directory.Exists(path) |
bool |
| 檔案 |
System.IO |
File.Exists(path) |
bool |
完整程式碼範例
using System;
using System.IO;
public class FilePathChecker
{
public static void Demo()
{
string dirPath = @"D:\Export";
string filePath = @"D:\Export\report.pdf";
// 1. 判斷目錄是否存在,不存在則建立
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
Console.WriteLine($"目錄已建立:{dirPath}");
}
else
{
Console.WriteLine($"目錄已存在:{dirPath}");
}
// 2. 判斷檔案是否存在
if (File.Exists(filePath))
{
Console.WriteLine($"檔案存在:{filePath}");
// 後續可進行讀取、複製、移動等操作
}
else
{
Console.WriteLine($"檔案不存在:{filePath}");
// 可選擇建立新檔或提示使用者
}
}
}
常見陷阱與最佳實務
- 路徑格式:建議使用
@"D:\Export" 逐字字串或 Path.Combine 組合路徑,避免跳脫字元錯誤。
- 權限問題:
CreateDirectory 可能因權限不足拋出 UnauthorizedAccessException,生產碼請包裹 try-catch。
- 競態條件:檢查存在與實際操作之間可能有時間差,關鍵操作建議直接嘗試執行並捕捉例外,而非單純依賴 Exists 結果。
- 相對路徑:ASP.NET 專案中請搭配
Server.MapPath("~/App_Data/Export") 轉為實體路徑。
延伸應用:封裝成通用輔助方法
public static class IOHelper
{
/// <summary>確保目錄存在,不存在則建立</summary>
public static void EnsureDirectory(string path)
{
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
}
/// <summary>安全刪除檔案(存在才刪,不拋出例外)</summary>
public static bool SafeDeleteFile(string filePath)
{
try
{
if (File.Exists(filePath))
{
File.Delete(filePath);
return true;
}
return false;
}
catch
{
return false;
}
}
}