unit TStreamReadBuffer;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ComCtrls, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    ListBox1: TListBox;
    RichEdit1: TRichEdit;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure LoadFromStream(Stream: TStream; myStrings: TStrings; Encoding: TEncoding);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

// BeginExample: TStreamReadBuffer
// Method: Classes.TStream.ReadBuffer
// BeginCode
{
This example requires TListBox, TMemo, TRichEdit, and
TButton controls placed on the form. The list box should
contain one or more items.  When the form becomes visible,
click on the button and the contents of the list box will be
transferred to a stream and then to the rich edit control.
}
procedure TForm1.Button1Click(Sender: TObject);
var
  TempStream : TMemoryStream;
begin
  TempStream := TMemoryStream.Create;
  ListBox1.Items.SaveToStream(TempStream);  // write list box contents to the
                                            // stream
  TempStream.Position := 0;      // reset to the beginning of the stream
//   RichEdit1.Lines.LoadFromStream( TempStream); // load stream contents into rich
                                               // edit control
  LoadFromStream(TempStream, RichEdit1.Lines, nil);
  TempStream.Free;
end;

procedure TForm1.LoadFromStream(Stream: TStream; myStrings: TStrings; Encoding: TEncoding);
var
  Size: Integer;
  Buffer: TBytes;
begin
  myStrings.BeginUpdate;
  try
    Size := Stream.Size - Stream.Position;
    SetLength(Buffer, Size);
    Stream.ReadBuffer(Pointer(Buffer)^, Size);

    Size := TEncoding.GetBufferEncoding(Buffer, Encoding);
    myStrings.Text := Encoding.GetString(Buffer, Size, Length(Buffer) - Size);
  finally
    myStrings.EndUpdate;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  ListBox1.Items.Add('Apples');
  ListBox1.Items.Add('Oranges');
  ListBox1.Items.Add('Pears');
end;
// EndCode
// EndExample: TStreamReadBuffer
end.
