How do I read a UTF8 encoded INI file?

user1527613 picture user1527613 · May 3, 2013 · Viewed 8.6k times · Source

I have an INI file in UTF-8 format.

I am using Delphi 2010 to read the INI file and populate a TStringGrid with the values in the INI file.

var
  ctr : Integer;
  AppIni : TIniFile;
begin
  AppIni := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'test.ini');
    for ctr := 1 to StringGrid1.RowCount do begin
        StringGrid1.Cells[0,ctr] := AppIni.ReadString('Column1','Row'+IntToStr(ctr),'');
        StringGrid1.Cells[1,ctr] := AppIni.ReadString('Column2','Row'+IntToStr(ctr),'');
    end;
  AppIni.Free;

The problem is that the unicode characters are appearing in the TStringGrid displaying 2 characters, rather than the 1 unicode character.

How do I resolve this?

Answer

David Heffernan picture David Heffernan · May 3, 2013

The TIniFile class is a wrapper of the Windows API for INI files. This does support Unicode INI files, but only if those files are encoded as UTF-16. Michael Kaplan has more details here: Unicode INI function; Unicode INI file?

So, you are out of luck with TIniFile. Instead you could use TMemIniFile which allows you to specify an encoding in its constructor. The TMemIniFile class is a native Delphi implementation of INI file support. There are various pros and cons between the two classes. In your situation, only TMemIniFile can serve your needs, so it's looking like its pros are going to outweigh its cons.