Search code examples
pascalfreepascallazarus

How to get the parent directory path of a path in FreePascal/Lazarus?


I have a path to a directory saved as a string, and wanted to know how I can easily and robustly extract the parent directory from this string?

I tried to see if there is some method for this in FileUtil and SysUtils, but haven't found anything so far.


Solution

  • The simplest way is to find the last path delimiter character and trim the source string. BTW there are some alternative:

    program Project1;
    
    uses
        sysutils;
    var
        sExe: string;
        sParent: string;
        sParentProper: string;
    begin
        sExe := ExtractFilePath(ParamStr(0)); // Get executable directory
        Writeln(sExe);
        sParent := IncludeTrailingPathDelimiter(sExe) + '..' + PathDelim; // Make parent path for executable
        Writeln(sParent);
        sParentProper := ExpandFileName(sParent); // Get absolute path based on relative path
        WriteLn(sParentProper);
        Readln;
    end.  
    

    And output is:

    C:\Users\nd\AppData\Local\Temp\
    C:\Users\nd\AppData\Local\Temp\..\
    C:\Users\nd\AppData\Local\
    

    So using this technique the proper way is ExpandFileName(IncludeTrailingPathDelimiter(sBasePath) + '..')

    PS: We are using only sysutils unit so it is pure FPC solution and it is not require any LCL libraries.