Code Samples for Businesses, Schools & Developers

First Published 5 Oct 2022


Here are two simple functions for obtaining the network (UNC) path for a mapped drive. Each function should be placed in a standard module.

1.   Using File System Object

      This requires the Microsoft Scripting Runtime reference library. It can be used to return the full UNC file path of files.

      CODE:

Function GetUNCPath(strMappedDrive As String) As String

'Requires Microsoft Scripting Runtime reference library

      Dim objFso As FileSystemObject
      Set objFso = New FileSystemObject
      Dim strDrive As String
      Dim strShare As String

      'Add trailing colon if missing
      If InStr(strMappedDrive, ":") = 0 Then strMappedDrive = Left(strMappedDrive, 1) & ":"

      'Separate the mapped letter from any following sub-folders
      strDrive = objFso.GetDriveName(strMappedDrive)

      'Debug.Print strDrive

      'find the UNC share name from the mapped letter
      strShare = objFso.Drives(strDrive).ShareName

      'The Replace function allows for sub-folders of the mapped drive
      GetUNCPath = Replace(strMappedDrive, strDrive, strShare)

      Set objFso = Nothing       'Destroy the file system object

End Function



      Typical usage:

?GetUNCPath("V")     'enter mapped drive only
\\Linx-12x64-tabl\c     'returns UNC path

?GetUNCPath("X:\DsoFile\eula.txt")     'enter full mapped path
\\COLIN-LAPTOP\G\DsoFile\eula.txt"     'returns full UNC file path




2.   Using WScript

      No additional references are required . This returns the network path ONLY.

      CODE:

Function GetNetworkPath(ByVal DriveName As String) As String

'No additional references required

      Dim objNetWork As Object
      Dim objDrives As Object
      Dim lngLoop As Long

      'Add trailing colon if missing
      If InStr(DriveName, ":") = 0 Then DriveName = Left(DriveName, 1) & ":"

      'Remove backslash & any subsequent text
      If InStr(DriveName, "\") > 0 Then DriveName = Left(DriveName, InStr(DriveName, "\") - 1)

      Set objNetWork = CreateObject("WScript.Network")
      Set objDrives = objNetWork.enumnetworkdrives

      For lngLoop = 0 To objDrives.count - 1 Step 2
            If UCase(objDrives.Item(lngLoop)) = UCase(DriveName) Then
                  GetNetworkPath = objDrives.Item(lngLoop + 1)
                  Exit For
            End If
      Next

End Function



      Typical usage:

?GetNetworkPath("V")     'enter mapped drive
\\Linx-12x64-tabl\c     'returns network path

?GetNetworkPath("X:\DsoFile\eula.txt")     'enter full mapped file path
\\COLIN-LAPTOP\G     'returns network path only





Colin Riddington           Mendip Data Systems                 Last Updated 5 Oct 2022



Return to Code Samples Page




Return to Top