TStringsEncoding (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example requires a TMemo control, two buttons and two textfields on the form. It demonstrates the new TStrings.Encoding property and the overloads of TStrings.LoadFromFile and SaveToFile that use it. Use this example to save lines in a specific encoding to a file and then load the file back in, reading the encoding. Notice that the ASCII format does not preserve wide characters.

Code

procedure TForm1.Button1Click(Sender: TObject);
var
  // You may need to change this path to suit your environment.
  Path: String;
begin
  Path:= Edit1.Text;
  Memo1.Lines.LoadFromFile(Path); // The encoding is read from the BOM and stored in the Encoding property.
  if Memo1.Lines.Encoding <> nil then
    Edit2.Text := Memo1.Lines.Encoding.EncodingName;
  Memo1.ScrollBars := ssVertical;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  // You may need to change this path to suit your environment.
  Path: String;
  myEncoding : TEncoding;
begin
  Path:= Edit1.Text;
  myEncoding := TEncoding.Default;
  if (Edit2.Text = 'ASCII') then myEncoding := TEncoding.ASCII;
  if (Edit2.Text = 'BigEndianUnicode') then myEncoding := TEncoding.BigEndianUnicode;
  if (Edit2.Text = 'Default') then myEncoding := TEncoding.Default;
  if (Edit2.Text = 'Unicode') then myEncoding := TEncoding.Unicode;
// Do not use UTF7 for this.  It does not have a BOM, and so the encoding cannot be detected on a load.
//  if (Edit2.Text = 'UTF7') then myEncoding := TEncoding.UTF7;
  if (Edit2.Text = 'UTF8') then myEncoding := TEncoding.UTF8;
  Memo1.Lines.SaveToFile(Path, myEncoding);
end;

Uses