Reputation: 367
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
Reputation: 1968
In newer versions of delphi you could use TDirectory
from IOUtils
TDirectory.GetParent(ExcludeTrailingPathDelimiter(YourPath))
Upvotes: 18
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
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