delphitsavedialog

TSaveDialog file extension and [ofOverwritePromt] issue


There is a simple question already about the idea of the TSaveDialog and [ofOverwritePromt] at Delphi overwrite existing file on save dialog.

So my issue/scenario is following:

So now I execute the program and call the dialog. If the file I select WITH MOUSE or KEYBOARD (without typing) exists then save dialog asks me to overwrite with the message:

save dialog

But if I do the same actions but type the filename like 'Test' without specifying the extension the save dialog does not confirm overwrite. I know that actually it returns another filename "C:\Users\xxx\Desktop\Test" instead of "C:\Users\xxx\Desktop\Test.pdf". It is kind of not nice if the dialog asks you to save the file, but you need to type the extension.. So usually I handle it like this:

repeat
  { Ask for the file if not silent }
  if not dlgSave.Execute then
    Exit;

  { Read the filename from the save dialog }
  LTempFile := dlgSave.FileName;
  if not SameText(ExtractFileExt(LTempFile), '.pdf') then
    begin
      { Add the extension }
      LTempFile := LTempFile + '.pdf';

      { As we bypassed the overwrite check in dialog do it now }
      if FileExists(LTempFile) then
        if MsgWarn(Format('%s already exists. Replace?', [ExtractFileName(LTempFile)]), mbOKCancel) <> mrOk then
          Continue;
    end;

  Break;
until False;

Is there a way to do that more elegant without customizing the standard dialog?


Solution

  • My guess is that you do not set DefaultExt, which is why you get a blank extension returned. Use this property and you won't get the problem. If you use multiple filters, use the OnFilterChange event. Here is one way to do it:

    procedure TFormMain.SigSaveDialogMainTypeChange(Sender: TObject);
    begin
      case (Sender as TSaveDialog).FilterIndex of
        0: (Sender as TSaveDialog).DefaultExt := 'pdf';
        1: (Sender as TSaveDialog).DefaultExt := 'txt';
      end;
    end;
    

    It also means you don't have to check for the extension and change it!