Mirror

How to save two TStringlists to the same stream (Views: 708)


Problem/Question/Abstract:

TStrings.LoadFromStream is assuming that itself consumes the rest of the stream! What if I want to save 2 stringlists to the same stream?

Answer:

That is as designed. Just use an intermediate stream to accomplish what you want. Or you can take the following approach using a string buffer:

{ ... }
var
  list1: TStringList;
  list2: TStringList;
  lng: cardinal;
  stream: TMemoryStream;
  tmpS: string;
begin
  list1 := TStringList.Create;
  list2 := TStringList.Create;
  try
    stream := TMemoryStream.Create;
    try
      {Assume there was code to get something into stream.
                        The layout of the stream is:
      size1|block1|size2|block2}
      {Read size of the 1st block}
      stream.Read(lng, SizeOf(lng));
      if lng > 0 then
      begin
        {if there are contents, read the block to tmpS}
        SetLength(tmpS, lng);
        stream.Read(tmpS[1], lng)
          {Assign tmpS to the Text property of list1}
        list1.Text := tmpS;
      end;
      {Same procedure for list2}
      stream.Read(lng, SizeOf(lng));
      if lng > 0 then
      begin
        SetLength(tmpS, lng);
        stream.Read(tmpS[1], lng)
          list2.Text := tmpS;
      end;
    finally
    end;
  finally
    list2.Free;
    list1.Free;
  end;
end;

<< Back to main page