Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • I have a TSaveDialog
  • I set the [ofOverwritePromt] in Options
  • I set the filter to "PDF (*.pdf)|*.pdf"
  • Filter index is set to 1

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?

like image 702
Z.B. Avatar asked Aug 18 '16 11:08

Z.B.


1 Answers

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!

like image 103
Dsm Avatar answered Nov 15 '22 20:11

Dsm