0

I need to start the external program c:\pro\prog1.exe from my project. The external program has its configuration file in the same directory c:\pro\prog1.ini. I do:

ShellExecute(NULL,L"open",L"c:\pro\prog1.exe" ,NULL,NULL,SW_SHOWDEFAULT);

Program c:\pro\prog1.exe starts, but it does not load its configuration file c:\pro\prog1.ini. It looks like I need to place the .ini file in the same directory where my host application is run from. This is not acceptable. So, how to start an external program and ask Windows to run it from its directory?

zx485
  • 28,498
  • 28
  • 50
  • 59
vico
  • 17,051
  • 45
  • 159
  • 315
  • Why don't you use the Process class and its ProcessStartInfo support class?. With that you could specify exactly the WorkingDirectory – Steve Nov 24 '16 at 09:53
  • you need use `CreateProcess` function - here exist parameter - `LPCTSTR lpCurrentDirectory` - this what you exactly need – RbMm Nov 24 '16 at 10:03
  • 3
    The 5th parameter is the startup directory: `ShellExecute(NULL, L"open", L"c:\\pro\\prog1.exe", NULL, L"c:\\pro\\", SW_SHOWDEFAULT);` – Barmak Shemirani Nov 24 '16 at 12:08
  • @Barmak Shemirani I'm ready to accept your answer if you post it. – vico Nov 24 '16 at 12:14
  • 4
    Alternatively, if *prog1.exe* is under your control, you could consider fixing it instead. Don't make it read it's configuration file from a current-working-directory relative path. Instead, use a fully qualified path by querying for the executable image's pathname. – IInspectable Nov 24 '16 at 12:35

1 Answers1

1

The 5th parameter in ShellExecute is the startup directory.

Alternatively "prog.exe" can use GetModuleFileName and PathRemoveFileSpec to find its own directory, as suggested in comments.

Note that some directories like "c:\\Program Files" and "c:\\Program Files (x86)" require elevated access to create/modify/delete files (for example during installation). A process without elevated access, can access files in protected directories with read-only flag. Otherwise Windows will redirect the path to a different directory if write-access is requested.

For normal execution, the *.exe should use "Documents" or "AppData" folder to read/write data.

Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77