jwz104
jwz104

Reputation: 367

How to get path to the parent folder of a certain directory?

When I would have this directory path:

C:\Program Files (x86)\Embarcadero\

The function I'm looking for should return:

C:\Program Files (x86)\

I've tried this code but it works only for files, not for directories:

function GetParentDirectory(const Path: string): string;
begin
  Result := ExpandFileName(Path);
end;

Does anyone know what should I use to return path to the parent folder of a certain directory ?

Upvotes: 13

Views: 15807

Answers (3)

Agustin Seifert
Agustin Seifert

Reputation: 1968

In newer versions of delphi you could use TDirectory from IOUtils

TDirectory.GetParent(ExcludeTrailingPathDelimiter(YourPath))

Upvotes: 18

Ken White
Ken White

Reputation: 125620

You can use a couple of ways:

From a folder name:

ExtractFilePath(ExcludeTrailingPathDelimiter('C:\Parent\Child\'));

From a file name:

ExtractFilePath(ExcludeTrailingPathDelimiter(ExtractFilePath('C:\Parent\Child\app.exe')));

Upvotes: 21

GabrielF
GabrielF

Reputation: 2121

Try this:

ExtractFileDir('C:\Path\Path2') gives 'C:\Path'

Note that

ExtractFileDir('C:\Path\Path2\') gives 'C:\Path\Path2'

Thanks to TLama:

ExtractFileDir(ExcludeTrailingBackslash('C:\Path\Path2')) gives 'C:\Path'
ExtractFileDir(ExcludeTrailingBackslash('C:\Path\Path2\')) gives 'C:\Path'

Upvotes: 6

Related Questions