Delphi – How read the content of file to a string in delphi XE

delphidelphi-2007delphi-xe

I'm migrating my application from delphi 2007 to delphi xe, but i having problems with a procedure which read a file (ascii) and store the content in a string

this is the code which work ok in delphi 2007

function LoadFileToStr(const FileName: TFileName): String;
var
  FileStream : TFileStream;
begin
  FileStream:= TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
    try
     if FileStream.Size>0 then
     begin
      SetLength(Result, FileStream.Size);
      FileStream.Read(Pointer(Result)^, FileStream.Size);
     end;
    finally
     FileStream.Free;
    end;
end;

but when execute this code in delphi XE the result are just symbols like '????????', i know which delphi xe is unicode so i change these lines

      SetLength(Result, FileStream.Size);
      FileStream.Read(Pointer(Result)^, FileStream.Size);

to

      SetLength(Result, FileStream.Size*2);
      FileStream.Read(Pointer(Result)^, FileStream.Size);

to store the content of the file in the unicode string but the result is the same.

how i can fix this procedure to read the content of this file?

Best Solution

you code does not work because you are reading the content of the file using a unicode string as buffer, so you are just moving bytes from the internal buffer of the TFileStream to the unicode string ignoring the encoding.

you can fix easily your procedure , just changing the result type to AnsiString

function LoadFileToStr(const FileName: TFileName): AnsiString;

but i will recommend you which you use the TFile.ReadAllText function instead which in a single line of code read the content of a file a also handle the encoding of the file.

Related Question