Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read From Text File in Delphi 2009

Tags:

delphi

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?

like image 438
AComputer Avatar asked Nov 13 '11 06:11

AComputer


People also ask

How do I read a text file?

To read from a text file Use the ReadAllText method of the My. Computer. FileSystem object to read the contents of a text file into a string, supplying the path. The following example reads the contents of test.


2 Answers

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); 
like image 110
Remy Lebeau Avatar answered Sep 20 '22 20:09

Remy Lebeau


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)
like image 45
Arjen van der Spek Avatar answered Sep 19 '22 20:09

Arjen van der Spek