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
).