thalm
thalm

Reputation: 2930

How to get the path of calling batch file in Delphi?

Is there a way in delphi to determine in which folder the batch file is which called the .exe?

For example there are 2 folders and a batch file:

c:\application\program.exe
c:\files\data.dat
c:\batch.bat

And the code of the batch file is:

application\program.exe -open "files\data.dat"

Then in Delphi i just get "files\data.dat" as commandArgs[0]. Is there a way to determine from where the batch file called me, so that i can build the full path?

I know that i can write in the batch file:

application\program.exe -open "%~dp0files\data.dat"

In this case the batch file resolves the path and passes the full path to delphi, but thats not the question.

Upvotes: 1

Views: 834

Answers (3)

Remko
Remko

Reputation: 7340

if the bat file is launching your exe then cmd.exe is the parent process and the batch file name is probably the cmdline of this cmd.exe. Start by veryfing with Process Explorer if this is true and if so get the parent process and kt's commandline programmatically

Upvotes: 2

David Heffernan
David Heffernan

Reputation: 613282

Is there a way in delphi to determine in which folder the batch file is which called the .exe?

That depends. If you know that the batch file lives in the parent directory of the directory which contains the executable, then you can do this:

ExeDir := ExtractFileDir(ParamStr(0));
ParentDir := ExtractFileDir(ExeDir);

On the other hand, if you have no special knowledge of where the batch file lives in relation to the executable, then there's no easy way to work out where it is. You can't expect to work it out from the working directory since that could, in general, be a directory other than the one containing the batch file.

So, if you do not control the batch file, then you can't expect to locate it easily and reliably. What's more, I'm not sure how you can be sure that there even is a batch file. The program could presumably be started by some other mechanism.

Upvotes: 2

Stijn Sanders
Stijn Sanders

Reputation: 36840

By using

application\program.exe -open "files\data.dat"

from the batch file, the process started to run program.exe should copy the current folder, so in this scenario you can use GetCurrentDir to read the full path of the batch file.

Upvotes: 1

Related Questions