Search Tools Links Login

Relative Path Function Gets the relative path of a file w.r.t. a directory


A reusable function that computes the relative path of a file with respect to a given directory


Examples will make the point clear, so here goes:



  1. GetRelativePath ("C:VB", "C:VBFile.ext")
    returns "File.ext"


  2. GetRelativePath ("C:VB", "C:VBProgramFile.ext")
    returns "ProgramFile.ext"


  3. GetRelativePath ("C:VB", "C:File.ext")
    returns "..File.ext"




It is useful to insert images and hyperlinks into webpages, given the filenames of the images and the HTML file.

Original Author: Manas Tungare

Inputs


  1. sBase
    Fully Qualified Path of the Base Directory


  2. sFile
    Fully Qualified Path of the File of which the relative path is to be computed.


Assumptions

Just remember to pass *complete* qualified paths to it. The CommonDialog.Filename property can be directly assigned in the call. e.g.

GetRelativePath ("C:VB", CommonDialog1.Filename)

Returns

Relative Path of sFile with respect to sBase.

Side Effects

None.

Code

Public Function GetRelativePath(sBase As String, sFile As String)
'------------------------------------------------------------
' Accepts : sBase= Fully Qualified Path of the Base Directory
'  sFile= Fully Qualified Path of the File of which
'   the relative path is to be computed.
' Returns : Relative Path of sFile with respect to sBase.
' Modifies: Nothing.
'------------------------------------------------------------
' Author : Manas Tungare (www.manastungare.com)
'------------------------------------------------------------
Dim Base() As String, File() As String
Dim I As Integer, NewTreeStart As Long, sRel As String
If Left(sBase, 3) <> Left(sFile, 3) Then
'Since the files lie on different drives, the relative
'filename is same as the Absolute Filename
GetRelativePath = sFile
Exit Function
End If

Base = Split(sBase, "")
File = Split(sFile, "")

While Base(I) = File(I)
I = I + 1
Wend

If I = UBound(Base) Then
'Then the Base Path is over, and the file lies
'in a subdirectory of the base directory.
'So simply append the rest of the path.
While I <= UBound(File)
  sRel = sRel + File(I) + ""
  I = I + 1
Wend
'Now remove the extra trailing "" we put earlier.
GetRelativePath = Left(sRel, Len(sRel) - 1)
Exit Function
End If

NewTreeStart = I
'The base path is not yet over, and we need to step
'back using the ".."
While I < UBound(Base)
sRel = sRel & ".."
I = I + 1
Wend

While NewTreeStart <= UBound(File)
sRel = sRel & File(NewTreeStart) + ""
NewTreeStart = NewTreeStart + 1
Wend
'Now remove the extra trailing "" we put earlier.
GetRelativePath = Left(sRel, Len(sRel) - 1)

End Function

About this post

Posted: 2002-06-01
By: ArchiveBot
Viewed: 92 times

Categories

Visual Basic 6

Attachments

No attachments for this post


Loading Comments ...

Comments

No comments have been added for this post.

You must be logged in to make a comment.