Reading unicode text file in delphi 2007 !

Hello,

i need to read a unicode text file and store it in string.

i failed to do that using LoadFromFile function already exists in delphi.

would u help me please ?
LVL 1
hintcoAsked:
Who is Participating?
 
MvanderKooijCommented:
I'm using the following code to read and write Unicode files with Delphi 2007. When I compile the same project in Delphi XE2 I do not use this but the unicode encoding. This way I can handle text files created with both ansi and unicode version of the same project.
(I use ifdefs to decide to use the unicode encoding for XE2 or those function for Delphi 2007 ansi)
 
function LoadAsUtf8(strFileName: AnsiString): AnsiString;
var
  Stream: TStream;
  bomHeader: array[0..2] of byte;

  strFileContents: UTF8String;
begin
  Stream := TFileStream.Create(strFileName, fmOpenRead);
  try
    Stream.Read(bomHeader, 3);
    if (bomHeader[0] = $EF) and (bomHeader[1] = $BB) and (bomHeader[2] = $BF) then begin
      SetLength(strFileContents, Stream.Size -3);
      Stream.ReadBuffer(Pointer(strFileContents)^, Stream.Size -3);
    end else begin
      Stream.Position := 0;
      SetLength(strFileContents, Stream.Size);
      Stream.ReadBuffer(Pointer(strFileContents)^, Stream.Size);
    end;
  finally
    Stream.Free;
  end;
  Result := Utf8ToAnsi(strFileContents);
end;

procedure SaveAsUtf8(strFileName, strText: AnsiString);
var
  Stream: TStream;
  bomHeader: array[0..2] of byte;
begin
  strText := AnsiToUtf8(strText);
  Stream := TFileStream.Create(strFileName, fmCreate);
  try
    bomHeader[0] := $EF;
    bomHeader[1] := $BB;
    bomHeader[2] := $BF;
    Stream.Write(bomHeader, 3);
    Stream.WriteBuffer(Pointer(strText)^, Length(strText));
  finally
    Stream.Free;
  end;
end;

Open in new window

0
 
hintcoAuthor Commented:
or i need a function converts unicode text file into ansi text file.
0
 
Emmanuel PASQUIERFreelance Project ManagerCommented:
here, you can find how to have some degree of Unicode-capability in applications made with Delphi pre 2009

http://stackoverflow.com/questions/383195/handling-a-unicode-string-in-delphi-versions-2007
0
 
hintcoAuthor Commented:
MvanderKooij:

thank you for the function but i need the same thing for UTF16
0
 
mlmccCommented:
This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.