Search code examples
delphidelphi-7

Changing the directory of Delphi OpenDialog


A little background of the program:
The program uses a tabbed interface to work on multiple files at the same time.
I'm trying to change the directory of the OpenDialog so every time I call open a file will show the directory of the file I am working on currently, but even when I set InitialDir to the file's path it always displays the last opened file directory, not the one I am setting it to.
I tried the following:

if Length(CurrentFileName) > 0 then
begin
  OpenFileDialog.InitialDir :='';
  SetCurrentDirectory(PChar(CurrentFileName));
  OpenFileDialog.InitialDir := ExtractFileDir(CurrentFileName);
end;
if OpenFileDialog.Execute then
...

Where CurrentFileName is the full path with the filename of the current tab's opened file. But no luck.

Is there any way to achieve this?

So for example:

tab1 has c:\mydir\file.txt opened
tab2 has d:\someotherdir\somefile.txt opened

If I move to tab1 and call the open function I the OpenDialog should show me the contents of c:\mydir\

I am using Delphi 7. Any help is appreciated.


Solution

  • I thought that

    if Length(CurrentFileName) > 0 then
      OpenFileDialog.FileName := ExtractFilePath(CurrentFileName);
    
    if OpenFileDialog.Execute
    

    was the way to go, but apparently the situation is slightly more involuted than I thought.

    Anyhow, I seriously doubt that

      OpenFileDialog.FileName := ExtractFilePath(CurrentFileName);
      OpenFileDialog.InitialDir := OpenFileDialog.FileName;
      SetCurrentDirectory(PChar(OpenFileDialog.FileName));
    

    will make you disappointed. Now the three chief ways of determining the dir says the same thing! A bit over-kill, but if Windows has changed its behaviour, it might be necessary.

    By the way, there is a bug in your code. SetCurrentDirectory wants a directory as argument, not a file name.