Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Advanced
Nov 29, 2001



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Generate a Relative Path Between Folders

You can use a Shell Light Weight API to generate a relative path by using this code:
Private Declare Function PathRelativePathToW _
Lib "shlwapi.dll" (ByVal pszPath As Long, _
ByVal pszFrom As Long, ByVal dwAttrFrom As _
Long, ByVal pszTo As Long, ByVal dwAttrTo _
As Long) As Boolean
Private Function GetRelativePath( _
sRelativePath As String, ByVal sPathFrom _
As String, ByVal sPathTo As String) As _
Dim bResult As Boolean
Const MAX_PATH As Long = 260
sRelativePath = Space(MAX_PATH)
' Set "dwAttr..." to vbDirectory for
' directories, 0 for files
bResult = PathRelativePathToW(StrPtr _
(sRelativePath), StrPtr(sPathFrom), _
vbDirectory, StrPtr(sPathTo), 0)
If bResult Then
sRelativePath = Left(sRelativePath, _
InStr(sRelativePath, vbNullChar) - 1)
sRelativePath = ""
End If
GetRelativePath = bResult
End Function
Private Sub Command1_Click()
Dim sRelative As String
' txtFromPath should contain the directory
' path to go from, txtToPath should contain
' the file path to go to.
' txtRelativePath will contain the result
If GetRelativePath(sRelative, _
txtFromPath.Text, txtToPath.Text) Then
txtRelativePath.Text = sRelative
txtRelativePath.Text = "Error"
End If
End Sub

PathRelativePathTo requires shlwapi.dll version 4.71 or higher, which ships with Internet Explorer 4. See http://msdn.microsoft.com/library/psdk/shellcc/shell/versions.htm for versioning details.
Phil Fresle
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date