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

4.8k views Asked by At

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.

3

There are 3 answers

1
Abelisto On BEST ANSWER

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.

0
Samuel Lampa On

Well, I of course figured it out only after asking about it here:

parentDirPath := FileUtil.ExtractFileNameOnly(
                   FileUtil.ChompPathDelim(theSubDirPath));

... will do!

The FileUtil.ChompPathDelim() part is necessary to "fool" FPC to believe the top folder is a "file" (so no trailing slash allowed).

0
jwdietrich On

An even simpler way to do this would be:

parentDirPath := ExtractFilePath(ExcludeTrailingPathDelimiter(thePath));

This works on the three major platforms (Linux, Mac OS X and Windows), and thePath may refer to a file or a folder.