Re: Get folder of your application

Posted by webmaster Guido on November 20, 2008

In Reply to Get folder of application with GetCurrentDir posted by Fred Green p15901 on November 18, 2008

: I can get the folder of my application with
: F := GetCurrentDir;

: This usually works out correctly, but not always, sometimes it gives me a totally different folder name! Is this a bug in Delphi, or in Windows? Maybe a bug with Windows Vista? If possible, how to cure it?

This is not a bug, because GetCurrentDir does NOT return the directory of your application. I know, often when this question is asked in a forum, that's the answer that you receive. But it's wrong, in a lot of cases it just works "by accident".

GetCurrentDir is derived from the Windows API function GetCurrentDirectory, that according to the help files "retrieves the current directory for the current process". Right after your application has started, this is the directory (folder) of the application's exe-file. But once you have opened a file with an OpenDialog or saved a file with a SaveDialog, and you have chosen a different directory, a call to GetCurrentDir returns that new directory! You can try it out:

Create a new form with two TButtons, a TLabel and a TOpenDialog. Write onclick event handlers for the buttons as follows:

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(GetCurrentDir);
end;
 
procedure TForm1.Button2Click(Sender: TObject);
begin
  if OpenDialog1.Execute then
    Label1.Caption := OpenDialog1.FileName;
end; 

Start this little program and click on Button1. You'll recieve a dialog window that shows the directory of your application, say "C:\Delphi\Sourcecode\TestGetCurrent" or similar.

Next click Button2. In the OpenDialog window, navigate to another directory, say "C:\Delphi", and select a file. The chosen filename appears in Label1.

Now click Button1 once again and you'll note that the "current directory" has changed; in our example, C:\Delphi will be shown!

But how to do it the right way?
Use the function ExtractFileDir(FileName); it returns the drive and directory parts from FileName. For FileName, give the name of your exe-file. Your exe-file is given by Application.Exename, so the code becomes:

var
  AppDir: string;
begin
  AppDir := ExtractFileDir(Application.ExeName);
  // Do something with AppDir, e.g.:
  ShowMessage(AppDir);
end;

 

Related articles