Path: GetDirectoryName

GetDirectoryName

Returns the directory information for the specified path string.



 Public Function GetDirectoryName(
	  ByRef Path As String ) As String

Parameters

Path
[ByRef] String. The path of a file or directory.

Return Values

String -  Directory information for Path, or empty string if Path denotes a root directory. Returns empty string if Path does not contain directory information.

Remarks

In most cases, the string returned by this method consists of all characters in the path up to but not including the last DirectorySeparatorChar or AltDirectorySeparatorChar. If the path consists of a root directory, such as "c:\", empty string is returned. Note that this method does not support paths using "file:". Because the returned path does not include the DirectorySeparatorChar or AltDirectorySeparatorChar, passing the returned path back into the GetDirectoryName method will result in the truncation of one folder level per subsequent call on the result string. For example, passing the path "C:\Directory\SubDirectory\test.txt" into the GetDirectoryName method will return "C:\Directory\SubDirectory". Passing that string, "C:\Directory\SubDirectory", into GetDirectoryName will result in "C:\Directory".
ExceptionCondition
ArgumentException The Path parameter contains invalid characters, is empty, or contains only white spaces.

Examples

The following code example demonstrates using the GetDirectoryName method.

Public Sub Main()
    Dim FilePath As String
    Dim DirectoryName As String
    Dim i As Long
    
    FilePath = "C:\MyDir\MySubDir\MyFile.txt"
    
    Do While Len(FilePath) > 0
        DirectoryName = Path.GetDirectoryName(FilePath)
        Debug.Print CorString.Format("GetDirectoryName('{0}') returns '{1}'", FilePath, DirectoryName)
        FilePath = DirectoryName
        
        If i = 1 Then
            FilePath = DirectoryName & "\" ' this will preserve the previous path
        End If
        
        i = i + 1
    Loop
End Sub

' This example code produces the following output.
'
'    GetDirectoryName('C:\MyDir\MySubDir\MyFile.txt') returns 'C:\MyDir\MySubDir'
'    GetDirectoryName('C:\MyDir\MySubDir') returns 'C:\MyDir'
'    GetDirectoryName('C:\MyDir\') returns 'C:\MyDir'
'    GetDirectoryName('C:\MyDir') returns 'C:\'
'    GetDirectoryName('C:\') returns ''

See Also

Project CorLib Overview

Class Path Overview