Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return the root directory of Delphi executable

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.

like image 776
Arch Brooks Avatar asked Sep 30 '15 15:09

Arch Brooks


3 Answers

You can obtain the full path to an application executable using:

ParamStr(0);

For a form based application, you have also the Application object available:

Application.ExeName;

To get the path to the file without the file name, you may consider to use ExtractFileDir or ExtractFilePath.

The difference between the two is that ExtractFilePath retuns the path with the last delimiter (/ or \) and ExtractFileDir truncates it.


As stated in the David Heffernan's comment, multiple calls to ExtractFileDir allow to get the parent directory:

Having C:\dev\w32\2015\BCSLBDemo\Win32\Debug\Project1.exe you can obtain C:\dev\w32\2015\BCSLBDemo like this:

ExtractFileDir(ExtractFileDir(ExtractFileDir(ParamStr(0))));
like image 90
fantaghirocco Avatar answered Oct 21 '22 14:10

fantaghirocco


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 ;-)

like image 13
Kromster Avatar answered Oct 21 '22 13:10

Kromster


You can obtain the full path to an application executable using:

Delphi 2010 declare Uses SWSystem;

Delphi Xe declare Uses IWSystem ;

showmessage(gsAppPath);

like image 1
Juliano Girardello Avatar answered Oct 21 '22 12:10

Juliano Girardello