Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How read the content of file to a string in delphi 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?

like image 392
DelphiNewbie Avatar asked May 23 '11 23:05

DelphiNewbie


2 Answers

You can achieve this with one line of code using ReadAllText function. Like this:

Uses IOUtils;

TFile.ReadAllText(FileName);

or

TFile.ReadAllText(FileName, s, TEncoding.ASCII) // if you want to force ASCII (other) encoding 

It will correctly detect ANSI, Unicode and binary files.

like image 99
Server Overflow Avatar answered Sep 24 '22 15:09

Server Overflow


You should take encoding into account, for example:

function LoadFileToStr(const FileName: TFileName): String;
var
  FileStream : TFileStream;
  Bytes: TBytes;

begin
  Result:= '';
  FileStream:= TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
  try
    if FileStream.Size>0 then begin
      SetLength(Bytes, FileStream.Size);
      FileStream.Read(Bytes[0], FileStream.Size);
    end;
    Result:= TEncoding.ASCII.GetString(Bytes);
  finally
    FileStream.Free;
  end;
end;


//test
procedure TForm2.Button1Click(Sender: TObject);
begin
  ShowMessage(LoadFileToStr('C:\autoexec.bat'));
end;
like image 40
kludg Avatar answered Sep 22 '22 15:09

kludg