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.
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))));
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 ;-)
You can obtain the full path to an application executable using:
Delphi 2010 declare Uses SWSystem;
Delphi Xe declare Uses IWSystem ;
showmessage(gsAppPath);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With