Selecting a directory with TOpenDialog

ple103 picture ple103 · Sep 14, 2011 · Viewed 94.8k times · Source

I'd really like to know the various ways I could select a directory with the TOpenDialog, whether it be downloading a new component or using what is provided by Delphi, but preferably using what is provided by Delphi.

Prior to this, I have been using the SelectDirectory command but I think it'd be a difficulty for the users of my program to look for the specified directory.

I think the SelectDirectory is 'weak' because it can be a long process when searching for the directory you want. Say for example, you want to navigate to the Application Data directory. How long or difficult would it be to navigate there? In the end, users may not even reach their desired directory.

I need something like this where the user can copy and paste directories into the directory address bar at the top there.

enter image description here

Thank you for all your answers.

Answer

Andreas Rejbrand picture Andreas Rejbrand · Sep 14, 2011

You can use the TFileOpenDialog (on Vista+):

with TFileOpenDialog.Create(nil) do
  try
    Options := [fdoPickFolders];
    if Execute then
      ShowMessage(FileName);
  finally
    Free;
  end;

Personally, I always use the TFileOpenDialog on Vista+ and fallback using the SelectDirectory (the good one!) on XP, like this:

if Win32MajorVersion >= 6 then
  with TFileOpenDialog.Create(nil) do
    try
      Title := 'Select Directory';
      Options := [fdoPickFolders, fdoPathMustExist, fdoForceFileSystem]; // YMMV
      OkButtonLabel := 'Select';
      DefaultFolder := FDir;
      FileName := FDir;
      if Execute then
        ShowMessage(FileName);
    finally
      Free;
    end
else
  if SelectDirectory('Select Directory', ExtractFileDrive(FDir), FDir,
             [sdNewUI, sdNewFolder]) then
    ShowMessage(FDir)