Delphi 2010是否具有LoadTextFromFile功能?

Jan*_*erk 5 delphi delphi-2010

在将一些代码从Delphi 7移植到Delphi 2010时,我正在重写我的LoadTextFromFile()函数.

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;
Run Code Online (Sandbox Code Playgroud)

当一个想法触及我的脑袋时:标准库中必定有这样的东西.许多用户想要将文本文件读入字符串,但我找不到这样的标准函数.我最接近的是使用TStringlist加载文本.但是A)创建一个TStringlist看起来没必要,B)我不想承受TStringlist的开销.

问题:Delphi 2010中是否有标准的LoadTextFromFile函数?

RRU*_*RUZ 14

是存在这样的一个功能德尔福2010年,被称为ReadAllText,是一部分TFile在declarated记录IOUtils单元.

检查此声明

class function ReadAllText(const Path: string): string; overload; inline; static;
class function ReadAllText(const Path: string; const Encoding: TEncoding): string; overload; inline; static;
Run Code Online (Sandbox Code Playgroud)

看这个样本

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.
Run Code Online (Sandbox Code Playgroud)

  • 我注意到TFile.ReadAllText在读取文件时会对文件进行独占锁定.我本来希望有一个fmShareDenyWrite锁. (2认同)