converting paths to relative or absolute
Posted: Mon Apr 03, 2006 7:30 am
Code updated for 5.20+
I needed this in a project. Maybe someone else find it useful too:
I needed this in a project. Maybe someone else find it useful too:
Code: Select all
;{ ===================================================================
;| ConvertToRelativePath(TargetPath$,ActualPath$)
;| Returns the path of TargetPath$ in relation to ActualPath$,
;| i.e creates a relative path to TargetPath$ with ActualPath$ as
;| starting point
;} ===================================================================
Procedure.s ConvertToRelativePath(TargetPath$,ActualPath$)
;***** TargetPath$ = Path to be converted (relative to ActualPath$)
If Left(TargetPath$,3)<>Left(ActualPath$,3)
;Target is located on a different drive -> no relative path possible
RelativePath$ = TargetPath$
ElseIf TargetPath$<>ActualPath$
;remove identical parts of both paths
backslashposition = 0
Repeat
TargetPath$ = Right(TargetPath$,Len(TargetPath$)-backslashposition)
ActualPath$ = Right(ActualPath$,Len(ActualPath$)-backslashposition)
backslashposition = FindString(TargetPath$,"\",1)
Until Left(TargetPath$,backslashposition) <> Left(ActualPath$,FindString(ActualPath$,"\",1))
;get number of remaining backslashes
backslashcount = CountString(ActualPath$,"\")
RelativePath$ = TargetPath$
;add relative paths
For i=0 To backslashcount
RelativePath$ = "..\" + RelativePath$
Next i
Else
;Target is located in the same directory
RelativePath$ = ".\"
EndIf
ProcedureReturn RelativePath$
EndProcedure
;{ ===================================================================
;| ConvertToAbsolutePath(TargetPath$,ActualPath$)
;| Returns the abolute path (with driveletter etc.) to the relative
;| TargetPath$ where ActualPath$ is the starting point
;} ===================================================================
Procedure.s ConvertToAbsolutePath(TargetPath$,ActualPath$)
;***** TargetPath$ = realtive to be converted in relation to ActualPath$)
If TargetPath$ = ".\" ;same as ActualPath
AbsolutePath$ = ActualPath$
ElseIf (Mid(TargetPath$, 2, 1) = ":") Or (Left(TargetPath$,2) = "\\") Or (Left(TargetPath$,1) = "%")
;Targetpath has a drive letter or is network drive or starts with environment variable
AbsolutePath$ = TargetPath$
Else ;some other relative path
If Right(ActualPath$, 1) = "\"
ActualPath$ = Left(ActualPath$,Len(ActualPath$)-1) ;remove last backslash
EndIf
While Left(TargetPath$,3) = "..\"
TargetPath$ = Right(TargetPath$, Len(TargetPath$)-3)
lastbackslashposition = 1
While FindString(ActualPath$,"\",lastbackslashposition+1)<>0
lastbackslashposition = FindString(ActualPath$,"\",lastbackslashposition+1)
Wend
ActualPath$ = Left(ActualPath$,lastbackslashposition-1) ;remove unecessary part
Wend
AbsolutePath$ = ActualPath$ + "\" + TargetPath$
EndIf
ProcedureReturn AbsolutePath$
EndProcedure