Delphi Read TXT File Tutorial

You can use the TStringList component and TFileStream component to read the contents of a txt file in Delphi. Here is a simple example code:

procedure ReadTxtFile(const FileName: string; var Content: TStringList);
var
  FileStream: TFileStream;
begin
  Content.Clear;
  FileStream := TFileStream.Create(FileName, fmOpenRead);
  try
    Content.LoadFromStream(FileStream);
  finally
    FileStream.Free;
  end;
end;

In the code above, we first create a TFileStream object to open the txt file, and then load the file content into a TStringList. Example code:

procedure TForm1.Button1Click(Sender: TObject);
var
  Content: TStringList;
begin
  Content := TStringList.Create;
  try
    ReadTxtFile('example.txt', Content);
    Memo1.Lines.Assign(Content);
  finally
    Content.Free;
  end;
end;

In the above example, we created a TStringList object to store the contents of a txt file and displayed it in the Memo1 control. You can modify and expand the above code according to your requirements.

bannerAds