Conversion between absolute and relative paths in Delphi

后端 未结 9 519
不思量自难忘°
不思量自难忘° 2020-11-30 01:18

Are there standard functions to perform absolute <--> relative path conversion in Delphi?

For example:

  • \'Base\' path is \'C:\\Projects\\Projec
9条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 01:37

    For what it's worth, my codebase uses SysUtils.ExtractRelativePath in one direction and the following home-grown wrapper coming back:

    function ExpandFileNameRelBaseDir(const FileName, BaseDir: string): string;
    var
      Buffer: array [0..MAX_PATH-1] of Char;
    begin
      if PathIsRelative(PChar(FileName)) then begin
        Result := IncludeTrailingBackslash(BaseDir)+FileName;
      end else begin
        Result := FileName;
      end;
      if PathCanonicalize(@Buffer[0], PChar(Result)) then begin
        Result := Buffer;
      end;
    end;
    

    You'll need to use the ShLwApi unit for PathIsRelative and PathCanonicalize.

    The call to PathIsRelative means that the routine is robust to absolute paths being specified.

    So, SysUtils.ExtractRelativePath can be your AbsToRel only the parameters are reversed. And my ExpandFileNameRelBaseDir will serve as your RelToAbs.

提交回复
热议问题