Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to load two text files into one TMemo component in Delphi?

Tags:

delphi

Let's say I have two text files (.txt) and I have a form with one TMemo Component on it. What would be the best way to quickly load both text files into the same Memo?

like image 417
Shaun Roselt Avatar asked Dec 23 '22 13:12

Shaun Roselt


1 Answers

Use a TStringList to load each file and then use the AddStrings method to transfer the contents to the memo.

var
  Tmp: TStringList;
...
Memo1.Lines.BeginUpdate;
try
  Memo1.Lines.Clear;
  Tmp := TStringList.Create;
  try
    Tmp.LoadFromFile(FileName1);
    Memo1.Lines.AddStrings(Tmp);

    Tmp.LoadFromFile(FileName2);
    Memo1.Lines.AddStrings(Tmp);
  finally
    Tmp.Free;
  end;
finally
  Memo1.Lines.EndUpdate;
end;

In fact, this can easily be generalised to a potentially useful method like this:

procedure AppendMultipleTextFiles(Dest: TStrings; const FileNames: array of string);
var
  FileName: string;
  Tmp: TStringList;
begin
  Dest.BeginUpdate;
  try
    Tmp := TStringList.Create;
    try
      for FileName in FileNames do
      begin
        Tmp.LoadFromFile(FileName);
        Dest.AddStrings(Tmp);
      end;
    finally
      Tmp.Free;
    end;
  finally
    Dest.EndUpdate;
  end;
end;

You could then use the method like so:

Memo1.Lines.Clear;
AppendMultipleTextFiles(Memo1.Lines, [FileName1, FileName2]);
like image 74
David Heffernan Avatar answered May 19 '23 22:05

David Heffernan