MemoryStream read/write and data length

6.6k Views Asked by At

I have a MemoryStream /BinaryWriter , I use it as following:

memStram = new MemoryStream();
memStramWriter = new BinaryWriter(memStram);

memStramWriter(byteArrayData);

now to read I do the following:

byte[] data = new byte[this.BulkSize];
int readed = this.memStram.Read(data, 0, Math.Min(this.BulkSize,(int)memStram.Length));

My 2 question is:

  1. After I read, the position move to currentPosition+readed , Does the memStram.Length will changed?
  2. I want to init the stream (like I just create it), can I do the following instead using Dispose and new again, if not is there any faster way than dispose&new: ;
memStram.Position = 0;
memStram.SetLength(0);

Thanks. Joseph

3

There are 3 best solutions below

0
On

1: After I read, the position move to currentPosition+readed , Does the memStram.Length will changed?

Reading doesn't usually change the .Length - just the .Position; but strictly speaking, it is a bad idea even to look at the .Length and .Position when reading (and often: when writing), as that is not supported on all streams. Usually, you read until (one of, depending on the scenario):

  • until you have read an expected number of bytes, for example via some length-header that told you how much to expect
  • until you see a sentinel value (common in text protocols; not so common in binary protocols)
  • until the end of the stream (where Read returns a non-positive value)

I would also probably say: don't use BinaryWriter. There doesn't seem to be anything useful that it is adding over just using Stream.

2: I want to init the stream (like I just create it), can I do the following instead using Dispose and new again, if not is there any faster way than dispose&new:

Yes, SetLength(0) is fine for MemoryStream. It isn't necessarily fine in all cases (for example, it won't make much sense on a NetworkStream).

0
On

No the lenght should not change, and you can easily inspect that with a watch variable

i would use the using statement, so the syntax will be more elegant and clear, and you will not forget to dispose it later...

0
On
  1. No; why should Length (i.e. data size) change on read?
  2. Yes; SetLength(0) is faster: there's no overhead with memory allocation and re-allocation in this case.