>> The D2009 TInitFile already uses the WritePrivateProfileStringW and
>> GetPrivateProfileStringW versions of the functions, but only work if
>> the ini file already exists and is Unicode. 
>>     
>
> Surprise! That works indeed with UTF-16, however if there is a UTF-8 
> BOM and data I cannot read a string, have you tested with UTF-8 as well?
>   
I tested right now and unfortunately don't work, but we can easily 
extend the class to support UTF8 BOM marked files.

interface
uses Inifiles;
type
  TMyUnicodeIniFile = class(TIniFile)
  private
    fIsUTF8: Boolean;
  public
    function ReadString(const Section, Ident, Default: string): string; 
override;
    procedure WriteString(const Section, Ident, Value: string); override;
    constructor Create(const aFileName: string);
  end;

implementation
uses Windows, Classes, sysutils, RTLConsts;

constructor TMyUnicodeIniFile.Create(const aFileName: string);
var f: TfileStream;
  i: integer;
const UnicodeBOM: word = $FEFF;
  UTF8BOM: Integer = $00BFBBEF;
begin
  if not fileexists(aFileName) then
  begin
    f := Tfilestream.Create(aFilename, fmCreate);
    try
      f.Write(UnicodeBOM, 2);
    finally
      f.Free;
    end
  end else
  begin
    f := Tfilestream.Create(aFilename, fmOpenRead);
    try
      i := 0;
      f.read(i, sizeof(i));
      fIsUTF8 := i and $00FFFFFF = UTF8BOM;
    finally
      f.Free;
    end;
  end;
  inherited;
end;

function TMyUnicodeIniFile.ReadString(const Section, Ident, Default: 
string): string;
begin
  result := inherited;
  if fIsUTF8 then
    result := utf8decode(result)
end;

procedure TMyUnicodeIniFile.WriteString(const Section, Ident, Value: 
string);
var s: Ansistring;
begin
  if fIsUTF8 then
  begin
    s := Utf8Encode(Value);
    if not WritePrivateProfileStringA(PAnsiChar(AnsiString((Section))), 
PAnsiChar(AnsiString((Ident))),
      PAnsiChar(s), PAnsiChar(AnsiString((FileName)))) then
      raise EIniFileException.CreateResFmt(@SIniFileWriteError, [FileName]);
  end else
    inherited;
end;
-- 
To unsubscribe or change your settings for TWSocket mailing list
please goto http://lists.elists.org/cgi-bin/mailman/listinfo/twsocket
Visit our website at http://www.overbyte.be

Reply via email to