'FileSystemObject: Retrieving folder name from UNC path
I don't know how to get the name of a folder in a UNC path with the FileSystemObject object. For example:
From "\\Server\FolderA" I would like to be able to get "FolderA". The method I was hoping would work is "GetBaseName" but it doesn't seem to work when the "IsRootFolder" property is True.
The following procedure:
Public Sub GetUNCFolderName()
Const stPathA As String = "\\Server\FolderA"
Const stPathB As String = "\\Server\FolderA\FolderB"
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Debug.Print "---------"
Debug.Print "Path A: " & stPathA
Debug.Print "GetAbsolutePathName: " & fso.GetAbsolutePathName(stPathA)
Debug.Print "GetBaseName : " & fso.GetBaseName(stPathA)
Debug.Print "IsRootFolder : " & fso.GetFolder(stPathA).IsRootFolder
Debug.Print "---------"
Debug.Print "Path B: " & stPathB
Debug.Print "GetAbsolutePathName: " & fso.GetAbsolutePathName(stPathB)
Debug.Print "GetBaseName : " & fso.GetBaseName(stPathB)
Debug.Print "IsRootFolder : " & fso.GetFolder(stPathB).IsRootFolder
End Sub
Returns this result:
---------
Path A: \\Server\FolderA
GetAbsolutePathName: \\Server\FolderA
GetBaseName :
IsRootFolder : True
---------
Path B: \\Server\FolderA\FolderB
GetAbsolutePathName: \\Server\FolderA\FolderB
GetBaseName : FolderB
IsRootFolder : False
As you can see "fso.GetBaseName(stPathA)" returns an empty string and "fso.GetBaseName(stPathB)" does not.
I appreciate any ideas you can give me.
Solution 1:[1]
It's probably not the best solution but I haven't been able to find one using only the FileSystemObject object. At least it's a lap that saves the problem. My solution goes through adding an if statement: If (fso.GetDrive(fso.GetDriveName(PathA)).DriveType = Network) And fso.GetFolder(PathA).IsRootFolder Then
Public Sub GetUNCFolderName()
Dim PathA As String, PathB As String
PathA = "\\Server\FolderA"
PathB = "\\Server\FolderA\FolderB"
Const Network = 3
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.GetDrive(fso.GetDriveName(PathA)).DriveType = Network) And fso.GetFolder(PathA).IsRootFolder Then
If VBA.Right$(PathA, 1) = "\" Then PathA = VBA.Left$(PathA, Len(PathA) - 1)
Debug.Print "PathA-1: " & VBA.Mid$(PathA, InStrRev(PathA, "\") + 1)
Else
Debug.Print "PathA-2: " & fso.GetBaseName(PathA)
End If
If (fso.GetDrive(fso.GetDriveName(PathB)).DriveType = Network) And fso.GetFolder(PathB).IsRootFolder Then
If VBA.Right$(PathB, 1) = "\" Then PathB = VBA.Left$(PathB, Len(PathB) - 1)
Debug.Print "PathB-1: " & VBA.Mid$(PathB, InStrRev(PathB, "\") + 1)
Else
Debug.Print "PathB-2: " & fso.GetBaseName(PathB)
End If
End Sub
Returns
PathA-1: FolderA
PathB-2: FolderB
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David |
