共用方式為


如何:在 Visual Basic 中剖析檔案路徑

FileSystem 物件提供剖析檔案路徑時的數種有用方法。

  • CombinePath 方法會採用兩個路徑,並傳回格式正確的合併路徑。

  • GetParentPath 方法會傳回所提供路徑之上層的絕對路徑。

  • GetFileInfo 方法會傳回 FileInfo 物件,這個物件可以進行查詢來判斷檔案的屬性 (例如其名稱和路徑)。

請不要根據副檔名來判斷檔案內容。 例如,檔案 Form1.vb 可能不是 Visual Basic 來源檔案。

判斷檔案的名稱和路徑

  • 使用 DirectoryName 物件的 NameFileInfo 屬性來判斷檔案的名稱和路徑。 這個範例會判斷名稱和路徑,並予以顯示。

    Dim testFile As System.IO.FileInfo
    testFile = My.Computer.FileSystem.GetFileInfo("C:\TestFolder1\test1.txt")
    Dim folderPath As String = testFile.DirectoryName
    MsgBox(folderPath)
    Dim fileName As String = testFile.Name
    MsgBox(fileName)
    

合併檔案的名稱和目錄以建立完整路徑

  • 使用 CombinePath 方法,並提供目錄和名稱。 這個範例會採用前一個範例中所建立的字串 folderPathfileName 、合併它們,並顯示結果。

    Dim fullPath As String
    fullPath = My.Computer.FileSystem.CombinePath(folderPath, fileName)
    MsgBox(fullPath)
    

另請參閱