AComputer
AComputer

Reputation: 529

Read From Text File in Delphi 2009

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

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

When I Run my application ,I click on the button and select my text file, in the memo i see :

"Œ ط¯ط± ط¢ظ…â€چظˆط²ط´â€Œ ع©â€چط´â€چط§ظˆط±ط²غŒâ€Œ: ط±"

the characters was not show correctly. How can I solve this problem?

Upvotes: 5

Views: 3476

Answers (2)

Arjen van der Spek
Arjen van der Spek

Reputation: 2660

It is possible to select an encoding format in the OpenTextFile Dialog. OpenTextFileDialog.Encodings represents a list of encodings that can be used, default list: ANSI, ASCII, Unicode, BigEndian, UTF8 and 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)

Upvotes: 5

Remy Lebeau
Remy Lebeau

Reputation: 597941

If the file does not have a UTF-8 BOM at the beginning, then you need to tell LoadFromFile() that the file is encoded, eg:

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

Upvotes: 12

Related Questions