wmercer
wmercer

Reputation: 1152

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.

Upvotes: 6

Views: 4781

Answers (4)

jachguate
jachguate

Reputation: 17203

This answer is valid for Delphi XE +

Use the TDirectory class of the IOutils unit, which have the method GetParent, like this::

uses IOUtils;

procedure TForm1.Button1Click(Sender: TObject);
var
  s: string;
begin
  s := 'c:\foo\bar';
  ShowMessage(TDirectory.GetParent(s));
end;

In older versions

Look at the other answers.

Upvotes: 2

Linas
Linas

Reputation: 5545

You can take a look at TPathBuilder record in SvClasses unit from delphi-oop library. This unit does not support Delphi 2007 but TPathBuilder implementation is compatible with this Delphi version. Example usage:

var
  LFullPath: string;
begin
  LFullPath := TPathBuilder.InitCustomPath('c:\foo\bar').GoUpFolder.AddFile('baz.txt').ToString;
  //LFullPath = c:\foo\baz.txt

Upvotes: 1

wmercer
wmercer

Reputation: 1152

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.

Upvotes: 11

Remy Lebeau
Remy Lebeau

Reputation: 596256

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.

Upvotes: 4

Related Questions