Directory path in Delphi?

I have the full path name for this folder, for example,

c:\foo\bar 

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

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

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

Is there a function that can perform path manipulation, for example. UpOneLevel (str) → str? I know that I can write one by dividing the line and deleting the last token, but I would prefer it to be a built-in / library function, so I don't get into the problem later if there are, for example, flashed backslashes.

+6
source share
4 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 path c:\foo .

+11
source

Take a look at ExtractFilePath() and ExtractFileDir() . They are available in almost all versions of Delphi, especially those that do not have TDirectory, IOUtils, etc.

And before anyone says this, these jobs will simply stop whether the path with the file name ends or not. ForceDirectories() uses them internally to go backward through the parent folder hierarchy, for example.

+4
source

This answer is valid for Delphi XE +

Use the TDirectory class of the IOutils module, which has a GetParent method, for example:

 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.

+2
source

You can see the TPathBuilder entry in the SvClasses unit from delphi-oop . This device does not support Delphi 2007, but the TPathBuilder implementation TPathBuilder compatible with this version of Delphi. Usage example:

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

All Articles