Conversion between absolute and relative paths in

2020-01-27 02:19发布

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\')  

标签: delphi path
9条回答
2楼-- · 2020-01-27 03:09

To convert to the absolute you have :

ExpandFileName

To have the relative path you have :

ExtractRelativePath

查看更多
趁早两清
3楼-- · 2020-01-27 03:12

I just brewed this together:

uses
  ShLwApi;

function RelToAbs(const ARelPath, ABasePath: string): string;
begin
  SetLength(Result, MAX_PATH);
  if PathCombine(@Result[1], PChar(IncludeTrailingPathDelimiter(ABasePath)), PChar(ARelPath)) = nil then
    Result := ''
  else
    SetLength(Result, StrLen(@Result[1]));
end;

Thanks to Andreas and David for calling my attention to the Shell Path Handling Functions.

查看更多
家丑人穷心不美
4楼-- · 2020-01-27 03:16

Another version of RelToAbs (compatible with all Delphi XE versions).

uses
  ShLwApi;

    function RelPathToAbsPath(const ARelPath, ABasePath: string): string;
    var Buff:array[0..MAX_PATH] of Char;
    begin
      if PathCombine(Buff, PChar(IncludeTrailingPathDelimiter(ABasePath)), PChar(ARelPath)) = nil then
        Result := ''
      else Result:=Buff;
    end;
查看更多
登录 后发表回答