[C#]使用 Path 類別取得檔案或目錄路徑資訊

  • 81012
  • 0
  • 2011-06-28

[C#]使用 Path 類別取得檔案或目錄路徑資訊

 

Path 類別 : 執行含有檔案或目錄路徑資訊的 String 執行個體 (Instance) 上的作業。 這些作業是以跨平台方式來執行的。

在 IO 命名空間中,Path 類別提供路徑與檔案路徑資訊的相關處理,封裝與路徑有關的檔案資訊,處理包含路徑資訊的字串,支援檔案名稱解析和路徑字串驗證等功能的方法。

Path 類別所提供的是靜態方法成員,下表列舉常用的方法成員,詳細方法成員請參考 Path 方法

名稱 說明
ChangeExtension 變更路徑字串副檔名
Combine 將兩個字串合併為一個路徑
GetDirectoryName 傳回指定路徑字串的目錄資訊
GetFileName 傳回指定路徑字串的檔案名稱和副檔名
GetFileNameWithoutExtension 傳回沒有副檔名的指定路徑字串的檔案名稱
GetExtension 傳回指定路徑字串的副檔名
GetFullPath 傳回指定路徑字串的絕對路徑
GetPathRoot 取得指定路徑的根目錄資訊
HasExtension 判斷路徑是否包括副檔名
IsPathRooted 取得值,指出指定路徑字串是否含有絕對或相對路徑資訊
GetTempPath 傳回目前使用者的暫存資料夾的路徑
GetInvalidFileNameChars 取得陣列,該陣列包含檔案名稱中不允許的字元
GetInvalidPathChars 取得陣列,該陣列包含路徑名稱中不允許的字元

 

底下是一個簡單的範例程式,點選 [選擇檔案] 按鈕,選擇檔案後,顯示透過 Path 類別做路徑解析的資料。

SNAGHTML729fee

範例程式碼

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;

namespace WinFormPath
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            if (this.openFileDlg.ShowDialog() == DialogResult.OK)
            {
                string strPath = openFileDlg.FileName;
                this.txtPath.Text = strPath;
                
                ListPathInfo(strPath);
            }
        }

        private void ListPathInfo(string strPath)
        {
            lstPathInfo.Items.Clear();
            lstPathInfo.Items.Add("路徑完整名稱 : " + Path.GetFullPath(strPath));
            lstPathInfo.Items.Add("路徑根目錄 : " + Path.GetPathRoot(strPath));
            lstPathInfo.Items.Add("路徑目錄資訊 : " + Path.GetDirectoryName(strPath));
            lstPathInfo.Items.Add("路徑檔案完整名稱 : " + Path.GetFileName(strPath));
            lstPathInfo.Items.Add("路徑檔案名稱 : " + Path.GetFileNameWithoutExtension(strPath));
            lstPathInfo.Items.Add("路徑檔案副檔名 : " + Path.GetExtension(strPath));
        }
    }
}

範例下載

WinFormPath.zip