TSaveTextFileDialog (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example uses a memo box, two buttons, an open dialog, and a save dialog on a form. When the application runs, the open dialog and save dialog filters are initialized, so that you can open and save *.txt files or files with any extension. Clicking the Open/Save button executes the open/save dialog. An exception is raised when trying to open a file that does not exist, or when trying to overwrite a file using the save dialog.

Code

procedure TForm1.Button1Click(Sender: TObject);
begin
  { Execute an open file dialog. }
  if OpenTextFileDialog1.Execute then
    { First check if the file exists. }
    if FileExists(OpenTextFileDialog1.FileName) then
    begin
      { If it exists, load the data into the memo box. }
      Memo1.Lines.LoadFromFile(OpenTextFileDialog1.FileName);
      Edit1.Text := OpenTextFileDialog1.Encodings[OpenTextFileDialog1.EncodingIndex];
    end
    else
      { Otherwise, raise an exception. }
      raise Exception.Create('File does not exist.');
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  { Execute a save file dialog. }
  if SaveTextFileDialog1.Execute then
    { First check if the file exists. }
    if FileExists(SaveTextFileDialog1.FileName) then
      { If it exists, raise an exception. }
      raise Exception.Create('File already exists. Cannot overwrite.')
    else
      { Otherwise, save the memo box lines into the file. }
      Memo1.Lines.SaveToFile(SaveTextFileDialog1.FileName);
  Edit1.Text := SaveTextFileDialog1.Encodings[SaveTextFileDialog1.EncodingIndex];
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  {
  Initialize the dialog filters to open/save *.txt files
  and also files with arbitrary extensions.
  }
  OpenTextFileDialog1.Filter := 'Text files (*.txt)|*.TXT|Any file (*.*)|*.*';
  SaveTextFileDialog1.Filter := 'Text files (*.txt)|*.TXT|Any file (*.*)|*.*';
end;

Uses