Generate a relative path from two physical paths

How can I get the relative path for a file from another physical path?

ie if I have one physical path of e:\\htdocs\newspages  and a second physical path of e:\\htdocs\images\news\129\test.jpg  how can I get the path of the file relative to the first path?  I need a vbscript function I can call, supplying the two paths which returns the relative path for the file.


Who is Participating?
monosodiumgConnect With a Mentor Commented:
The fn below does it. You might want to make it more robust by replacing any "/" in the paths with "\", checking for existing "..\", handling the presence of a terminating \ in either or both paths properly.

Function RelPath(sRefPath, sPath) As String
 Dim aRelPath As Variant
 Dim aPath As Variant

  aRelPath = Split(sRefPath, "\")
  aPath = Split(sPath, "\")
 Dim nCommonCount As Integer
 'nShorterPathLen is the maximum possible common length i.e. the lenght of the shorter path
 Dim nShorterPathLen As Integer
 If UBound(aRelPath) > UBound(aPath) Then
   nShorterPathLen = UBound(aPath)
   nShorterPathLen = UBound(aRelPath)
 End If
While nCommonCount <= nShorterPathLen And aRelPath(nCommonCount) = aPath(nCommonCount)
  nCommonCount = nCommonCount + 1

Dim sFinalPath As String
sFinalPath = ""
Dim nIdx As Integer

'The number of "..\" elements required is the Ubound(aRelPath) - nShorterPathLen
For nIdx = 0 To UBound(aRelPath) - nCommonCount
  sFinalPath = sFinalPath + "..\"
Next nIdx

'The number of tail elements to pick up from aPath is Ubound(aPath) -  - nShorterPathLen
For nIdx = nShorterPathLen To UBound(aPath)
  sFinalPath = sFinalPath + aPath(nIdx) + "\"
Next nIdx

'Strip of the extra trailing \:
sFinalPath = Left(sFinalPath, Len(sFinalPath) - 1)

RelPath = sFinalPath
End Function
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.