System.IO.Path 提供**跨平台、安全、效能佳**的靜態方法處理檔案/目錄路徑。手工 Split/Substring 易出錯(分隔符、相對路徑、UNC、根目錄邊界情況)。本文以實戰範例整理 15 大核心方法。
string filePath = @"E:\Randy\0528\中文目錄\JustTest.rar";
// Windows 路徑分隔符為 '\',@ 字串字面值避免雙重跳脫
| 方法 | 回傳值說明 | 範例輸出 |
|---|---|---|
ChangeExtension(path, ".txt") | 變更副檔名(含點) | E:\Randy\0528\中文目錄\JustTest.txt |
GetDirectoryName(path) | 目錄路徑(不含檔名) | E:\Randy\0528\中文目錄 |
GetExtension(path) | 副檔名(含點) | .rar |
GetFileName(path) | 檔名+副檔名 | JustTest.rar |
GetFileNameWithoutExtension(path) | 純檔名 | JustTest |
GetPathRoot(path) | 根目錄/磁碟機 | E:\ |
GetRandomFileName() | 亂數檔名(8.3 格式) | ct2h5b2h.sed |
GetTempFileName() | 建立實體暫存檔,回傳完整路徑 | C:\Users\Randy\AppData\Local\Temp\tmpAD.tmp |
GetTempPath() | 系統暫存目錄路徑 | C:\Users\Randy\AppData\Local\Temp\ |
HasExtension(path) | 是否有副檔名 | True |
IsPathRooted(path) | 是否為絕對路徑 | True |
Combine(path1, path2, ...) | 安全合併路徑(自動處理分隔符) | Path.Combine("E:\Dir", "Sub", "File.txt") → E:\Dir\Sub\File.txt |
GetFullPath(relativePath) | 相對轉絕對路徑(基於 CurrentDirectory) | Path.GetFullPath("..\Data") |
GetInvalidPathChars() | 不可用於路徑的字元陣列 | { '"', '<', '>', '|', ... } |
GetInvalidFileNameChars() | 不可用於檔名的字元陣列 | { '\0', '"', '<', '>', '|', ':', '*', '?', '\\', '/' } |
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string logDir = Path.Combine(baseDir, "Logs", DateTime.Now.ToString("yyyyMM"));
Directory.CreateDirectory(logDir); // 遞迴建立,存在不報錯
string GetUniquePath(string dir, string prefix, string ext)
{
string path;
do { path = Path.Combine(dir, prefix + Path.GetRandomFileName() + ext); }
while (File.Exists(path));
return path;
}
string normalized = Path.GetFullPath(path).Replace('\\', Path.DirectorySeparatorChar);
// .NET Core / .NET 5+ 自動處理跨平台分隔符
string SanitizeFileName(string name)
{
foreach (char c in Path.GetInvalidFileNameChars())
name = name.Replace(c, '_');
return name;
}
| 類別 | 職責 | 靜態/實例 |
|---|---|---|
Path | 純字串路徑運算,**不存取磁碟** | 靜態 |
Directory | 目錄建立/刪除/列舉/屬性,**存取磁碟** | 靜態 |
DirectoryInfo | 目錄實例操作,適合多次操作同目錄 | 實例 |
File | 檔案建立/複製/移動/刪除/讀寫,**存取磁碟** | 靜態 |
FileInfo | 檔案實例操作,適合多次操作同檔案 | 實例 |
Path.DirectorySeparatorChar:Windows '\\'、Linux/macOS '/'。Path.PathSeparator:環境變數分隔符,Windows ';'、Unix ':'。Path.GetFullPath 在 Linux 會解析符號連結,Windows 則不會。Path.Combine。System.IO.Path 是路徑處理的**唯一正統**。掌握上述 15 大方法與 Combine/GetFullPath 兩大合成神器,即可杜絕路徑字串處理 Bug,打造跨平台相容的檔案系統操作代碼。