Reading from a text file in Delphi 2009

I have a text file encoded in UTF8 and I create an application in delphi 2009 with opendialoge, a note and a button and write this code:

if OpenTextFileDialog1.Execute then
   Memo1.Lines.LoadFromFile(OpenTextFileDialog1.FileName);

When I launch my application, I click on the button and select my text file, in the note I see:

"Œ ط ط ط ط ¢ ¢ ظ ظ ظ ع ع ع â â â Œ چط ط ط ط Œ Œ Œ Œ ط ط ط ط ط ط ط ط ط ط ط ط ط ط ط → → → →

characters were not displayed correctly. How can I solve this problem?

+5
source share
2 answers

If at the beginning the file does not have the UTF-8 specification, you need to report LoadFromFile()that the file is encoded, for example:

Memo1.Lines.LoadFromFile(OpenTextFileDialog1.FileName, TEncoding.UTF8); 
+12
source

OpenTextFile . OpenTextFileDialog.Encodings , , : ANSI, ASCII, Unicode, BigEndian, UTF8 UTF7.

// Optionally add Encoding formats to the list:
FMyEncoding := TMyEncoding.Create;
OpenTextFileDialog1.Encodings.AddObject('MyEncoding', FMyEncoding);
// Don't forget to free FMyEncoding


var
  Encoding : TEncoding;
  EncIndex : Integer;
  Filename : String;
begin
  if OpenTextFileDialog1.Execute(Self.Handle) then
    begin
    Filename := OpenTextFileDialog1.FileName;

    EncIndex := OpenTextFileDialog1.EncodingIndex;
    Encoding := OpenTextFileDialog1.Encodings.Objects[EncIndex] as TEncoding;
    // No Encoding found in Objects, probably a default Encoding:
    if not Assigned(Encoding) then
      Encoding := StandardEncodingFromName(OpenTextFileDialog1.Encodings[EncIndex]);

    //Checking if the file exists
    if FileExists(Filename) then
      //Display the contents in a memo based on the selected encoding.
      Memo1.Lines.LoadFromFile(FileName, Encoding)
+5

All Articles