Tanya
Tanya

Reputation: 119

Unexpected MemoryStream behavior

I am reading and writing to the same MemoryStream.

Something like this(possible compilation mistakes):

MemoryStream stream = new MemoryStream();
stream.Write("1234",0,4);
stream.Position -= 4;
stream.Read(buffer,0,4);

Why do I HAVE to move Position? Why it is not separate to read and write?

Is there any other Stream that can be used?

Upvotes: 0

Views: 147

Answers (1)

CodeCaster
CodeCaster

Reputation: 151594

Because that's how streams are supposed to work. You have one position, see it as a cursor, set at a point in the stream at which you can read or write. Reading and writing both advance this position.

If you're merely using a MemoryStream to exchange data between callers, as a pseudo IPC mechanism, then perhaps some better way exists to do so.

Upvotes: 2

Related Questions