How to move a string into a TMemoryStream or TFileStream.

By: Corbin Dunn

Abstract: Sometimes you need to move strings into TStreams. This describes how to easily accomplish this task.

Question: How do I move a string into a TMemoryStream (or a TFileStream)?

Answer: Here is a code sample of how to do this with a TMemoryStream. It could easily be extended to work with a TFileStream too:

procedure TForm1.Button1Click(Sender: TObject);
var
  SourceString: string;
  MemoryStream: TMemoryStream;
begin
  SourceString := 'Hello, how are you doing today?';
  MemoryStream := TMemoryStream.Create;
  try
    // Write the string to the stream. We want to write from SourceString's
    // data, starting at a pointer to SourceString (this returns a pointer to
    // the first character), dereferenced (this gives the actual character).
    MemoryStream.WriteBuffer(Pointer(SourceString)^, Length(SourceString));
    // Go back to the start of the stream
    MemoryStream.Position := 0;
    // Read it back in to make sure it worked.
    SourceString := 'I am doing just fine!';
    // Set the length, so we have space to read into
    SetLength(SourceString, MemoryStream.Size);
    MemoryStream.ReadBuffer(Pointer(SourceString)^, MemoryStream.Size);
    Caption := SourceString;
  finally
    MemoryStream.Free;
  end;
end;


Server Response from: ETNASC01