首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 從字串分離檔案路徑、檔名與副檔名 — Substring/LastIndexOf 實用技巧

     編輯:關於C語言

關鍵程式碼


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。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved