Return the root directory of Delphi executable

Arch Brooks picture Arch Brooks · Sep 30, 2015 · Viewed 28.1k times · Source

I have a Delphi application executing and when I call GetCurrentDir the following returns:

C:\dev\w32\2015\BCSLBDemo\Win32\Debug

When I call ExtractFileDir(GetCurrentDir()) I receive the following:

C:\dev\w32\2015\BCSLBDemo\Win32

What I desire is C:\dev\w32\2015\BCSLBDemo

function RetRoot: string;
var
  i: Integer;
  buf: string;
begin
  Result := '';
  buf := ExtractFileDir(GetCurrentDir());
  i := Length(buf);
  repeat
    dec(i);
  until (buf[i] = '\') or (i < 3);
  if buf[i] = '\' then
  begin
    Delete(buf, i, Length(buf));
    Result := buf;
  end;
end;

I wrote this function to get the desired result. I would like to know if there is a better approach to accomplish retrieving the root directory of a Delphi executable.

Answer

Kromster picture Kromster · Sep 30, 2015

There's another way:

ExpandFileName(GetCurrentDir + '\..\..\'); // Current folder
ExpandFileName(ExtractFileDir(Application.ExeName) + '\..\..\'); // Exe folder

C:\dev\w32\2015\BCSLBDemo

Will take you two levels up as you can see.

Of course this only answer the "how to get 2 levels up" question. The question about Exe root is kind of non-sense. You might just need to configure your project settings to not make the Win32\Debug folders or move your data files into there ;-)