Are there standard functions to perform absolute <--> relative path conversion in Delphi?
For example:
- 'Base' path is
'C:\Projects\Project1\'
- Relative path is
'..\Shared\somefile.pas'
- Absolute path is
'C:\Projects\Shared\somefile.pas'
I am looking for something like this:
function AbsToRel(const AbsPath, BasePath: string): string;
// '..\Shared\somefile.pas' =
// AbsToRel('C:\Projects\Shared\somefile.pas', 'C:\Projects\Project1\')
function RelToAbs(const RelPath, BasePath: string): string;
// 'C:\Projects\Shared\somefile.pas' =
// RelToAbs('..\Shared\somefile.pas', 'C:\Projects\Project1\')
I am not too certain if this is still needed after 2+ years, but here is a way to get the Relative to Absolute (As for Absolute to Relative I would suggest philnext's
ExtractRelativePath
answer):Unit: IOUtils
Parent: TPath
It will return the full, absolute path for a given relative path. If the given path is already absolute, it will just return it as is.
Here is the link at Embarcadero: Get Full Path
And here is a link for Path Manipulation Routines
For what it's worth, my codebase uses
SysUtils.ExtractRelativePath
in one direction and the following home-grown wrapper coming back:You'll need to use the
ShLwApi
unit forPathIsRelative
andPathCanonicalize
.The call to
PathIsRelative
means that the routine is robust to absolute paths being specified.So,
SysUtils.ExtractRelativePath
can be yourAbsToRel
only the parameters are reversed. And myExpandFileNameRelBaseDir
will serve as yourRelToAbs
.Should be available since Delphi XE.
Check if your solution will works with Relative Path To Full Path in case when you change current directory. This will works:
An alternate solution for
RelToAbs
is simply:I would use
PathRelativePathTo
as the first function andPathCanonicalize
as the second. In the latter case, as argument you pass the string sum of the base path and the relative path.Of course, if you use a non-Unicode version of Delphi (that is, <= Delphi 2007), you need to use the Ansi functions (
*A
) instead of the Unicode functions (*W
).