user1593881
user1593881

Reputation:

Writing strings and bytes to a MemoryStream

How to write 'Hello World' string, clrf, and some random 10 bytes to a memory stream in Delphi?

Upvotes: 4

Views: 25872

Answers (2)

bummi
bummi

Reputation: 27367

var
  ms: TMemoryStream;
  s: String;
  b: array[0..9] of Byte;
  i: Integer;
begin
  ms := TMemoryStream.Create;
  try
    s := 'Hello World' + #13#10;
    ms.Write(s[1], Length(s) * SizeOf(Char));
    for i := 0 to 9 do
      b[i] := Random(256);
    ms.Write(b[0], 10);
    // ms.SaveToFile('C:\temp\test.txt');

    {
    ms.Memory can be used for free access e.g.
    // build an empty buffer 5 characters
    s := '';
    SetLength(s,5);
    ms.Position := 5;
    // the position after which we want to copy
    i := Length('Hallo ')*SizeOf(Char);
    // copy bytes to string
    Move(TByteArray(ms.Memory^)[i],s[1],Length(s) * SizeOf(Char));
    Showmessage(s); // Display's "World"
    }


  finally
    ms.Free;
  end;    
end;

Upvotes: 5

David Heffernan
David Heffernan

Reputation: 612794

I would consider using a binary writer for this task. This is a higher level class that takes care of the details of getting data into the stream.

var
  Stream: TMemoryStream;
  Writer: TBinaryWriter;
  Bytes: TBytes;
....
Stream := TMemoryStream.Create;
try
  Writer := TBinaryWriter.Create(Stream);
  try
    Writer.Write(TEncoding.UTF8.GetBytes('Hello World'+sLineBreak));
    //if you prefer, use a different encoding for your text
    Bytes := GetRandomBytes(10);//I assume you can write this
    Writer.Write(Bytes);
  finally
    Writer.Free;
  end;
finally
  Stream.Free;
end;

I expect that your real problem is more involved than this. The benefit of using the writer class is that you insulate yourself from the gory details of spewing data to the stream.

Upvotes: 10

Related Questions