Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Delphi 2010 have a LoadTextFromFile function?

While porting some code from Delphi 7 to Delphi 2010 I was rewriting my LoadTextFromFile() function.

function LoadTextFromFile(const aFullFileName: string): string;
var
  lBuffer:     TBytes;
  lEncoding:   TEncoding;
  lFileStream: TFileStream;
  lSize:       Integer;

begin

  if not FileExists(aFullFileName) then
  begin
    raise Exception.Create('File "' + aFullFileName + '" not found.');
  end;

  lFileStream := TFileStream.Create(aFullFileName, fmOpenRead + fmShareDenyNone);
  try

    if lFileStream.Size <= 0 then
    begin
      Result := '';
    end
    else
    begin

      lSize := lFileStream.Size - lFileStream.Position;

      SetLength(lBuffer, lSize);

      // Read file into TBytes buffer
      lFileStream.Read(lBuffer[0], lSize);

      // Read encoding from buffer
      TEncoding.GetBufferEncoding(lBuffer, lEncoding);

      // Get string from buffer
      Result := lEncoding.GetString(lBuffer);

    end;

  finally
    lFileStream.Free;
  end;

end;

When a thought was hitting my head: there must be something like this in the standard library. Many users want to read a text file into a string, but I could not find such a standard function. The closest I came was using TStringlist to load text. But A) creating a TStringlist looks unnecessary and B) I don't want to suffer the overhead from TStringlist.

Question: is there a standard LoadTextFromFile function in Delphi 2010?

like image 543
Jan Derk Avatar asked Aug 15 '10 10:08

Jan Derk


2 Answers

Yes exist one function like that in Delphi 2010, is called ReadAllText and is part of the TFile record declarated in the IOUtils unit.

Check this declaration

class function ReadAllText(const Path: string): string; overload; inline; static;
class function ReadAllText(const Path: string; const Encoding: TEncoding): string; overload; inline; static;

see this sample

program Project80;

{$APPTYPE CONSOLE}

uses
  IOUtils,
  SysUtils;
Var
 Content : string;
begin
  try
    Content:=TFile.ReadAllText('C:\Downloads\test.css'); //load the text of the file in a single line of code
    //Content:=TFile.ReadAllText('C:\Downloads\test.css',TEncoding.UTF8); //you can an encoding too.
    Writeln(Content);
    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
like image 106
RRUZ Avatar answered Nov 28 '22 18:11

RRUZ


TStringStream.LoadFromStream/file ? Anyway very large strings are always a bit wasteful. You have to be very careful to not accidentally copy it.

like image 28
Marco van de Voort Avatar answered Nov 28 '22 19:11

Marco van de Voort