Wednesday, 18 August 2010

TIniFile looses unicode characters

We've recently started converting code from Delphi 2007 to Delphi 2010 and we noticed that the TInifile looses unicode characters when we try to save an unicode string into the file. The file is UTF-8 encoding and when we try to save characters like 'ó', 'ç', 'á', etc., they don't appear or some unrecognised characters are shown into the ini file instead of the normal ones.
If the file is ANSI encoded and we try yo use the Tinifile, it will work fine with the unicode characters but not if the ini file is converted to UTF-8.
To solve this, we can use the TMemIniFile class. TMemInifile has an overload for the constructor that allows you to pass the encoding used for the file. The code example to solve this is the following:
procedure TForm1.Button1Click(Sender: TObject);
var
    inifile : TMemIniFile;
    desc : string;
    temp : WideString;
begin
   inifile := TMemIniFile.Create('C:\fileIni.ini', TEncoding.UTF8);
   temp := 'óáç';
   desc := string(temp);
   inifile.WriteString('Section', desc, 'S');
   inifile.UpdateFile;
   inifile.Free;
end;

0 comments:

Post a Comment