Unixode TStringList.LoadFromFile

I'm trying to open a txt file in a StringList, but if I open the UTF-8 format, it doesn't load, it's confusing because I have Unicode XE2, am I missing something stupid here?

A simple example

Sl := tStringList.Create;

SL.LoadFromFile(sFilePath);

For i =0 to SL.Count -1 do
  foo

      

but String is not loaded when the txt file is UTF-8, but works fine when it is in ANSI format.

+3
delphi delphi-xe2 tstringlist


source to share


2 answers


If your UTF-8 file has a BOM, then loading a UTF-8 file containing an invalid UTF-8 byte sequence will produce empty results with no exceptions or refusal indications. This is the "feature" of Delphi file handling. So if you see this result and your file has a valid BOM, check the content.



+1


source to share


TStringList.LoadFromFile

will try to infer the encoding from the file byte mark (BOM). If no specification exists, ANSI encoding is assumed.

In your case, it seems clear that there is no BOM, so you must specify LoadFromFile

which encoding to use. Do this by specifying the encoding as the second argument passed to LoadFromFile

:



SL.LoadFromFile(sFilePath, TEncoding.UTF8);

      

+6


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics