共用方式為


如何:在 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)
    

另請參閱