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?
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.
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With