關鍵程式碼
string fullPath = textBox1.Text; // 例:C:\Folder\Sub\file.txt
string path = fullPath.Substring(0, fullPath.LastIndexOf("\\"));
// path = "C:\Folder\Sub"
string name = fullPath.Substring(
fullPath.LastIndexOf("\\") + 1,
fullPath.LastIndexOf(".") - fullPath.LastIndexOf("\\") - 1);
// name = "file"
string ext = fullPath.Substring(fullPath.LastIndexOf(".") + 1);
// ext = "txt"
MessageBox.Show(
"檔案路徑:" + path + "\n檔案名:" + name + "\n副檔名:" + ext,
"資訊", MessageBoxButtons.OK, MessageBoxIcon.Information);
更穩健的替代方案
using System.IO;
string path = Path.GetDirectoryName(fullPath);
string name = Path.GetFileNameWithoutExtension(fullPath);
string ext = Path.GetExtension(fullPath).TrimStart('.');
Path 類別自動處理路徑分隔符差異、UNC 路徑、相對路徑等邊界情況。
- 建議生產環境優先使用
System.IO.Path。