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?