Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory path manipulation in Delphi?

I have the full path name of a given folder for e.g.

c:\foo\bar

Now I would like to reference a file inside c:\foo named baz.txt,

c:\foo\bar\..\baz.txt

I am currently using the .. path operator to go down one level and get the file that I need.

Is there a function that can do path manipulations, for e.g. UpOneLevel(str) -> str ? I know I can write one by splitting the string and removing the last token, but I would rather it be a built-in / library function so I don't get into trouble later if there are for e.g. escaped backslashes.

like image 518
wmercer Avatar asked Feb 01 '13 03:02

wmercer


2 Answers

Use the ExpandFileName function:

var
  S: string;
begin
  S := 'c:\foo\bar\..';
  S := ExpandFileName(S);
  ShowMessage(S);
end;

The message from the above example will show the c:\foo path.

like image 51
wmercer Avatar answered Sep 22 '22 00:09

wmercer


Look at ExtractFilePath() and ExtractFileDir(). These are available in just about all Delphi versions, particularly those that do not have TDirectory, IOUtils, etc.

And before anyone says it, these work just fine whether the path ends with a filename or not. ForceDirectories() uses them internally to walk backwards through a hierarchy of parent folders, for example.

like image 43
Remy Lebeau Avatar answered Sep 20 '22 00:09

Remy Lebeau