Embedding of size in Stream I am embedding my size in a Stream in the first 4 byte.  When I think about it, it should be possible to do it better, but that depends.

Here is how I currently do it:

bsize = ms.Length;
tcp.GetStream().Write(BitConverter.GetBytes(bsize), 0, intsize);
tcp.GetStream().Write(ms.GetBuffer(), 0, (int)bsize);


As you can see, it works and it's nothing weird.  I just send 2 streams, the first being the length and the other being the data.

So, there aren't many things that can be done to improve or even change this.

But my idea is: why use 2 streams when you can probably embed the size immediately on the second, so you only need to write it once?

Sadly, I am not sure how to do that, or if it's even an improvement.  Here is my testing code to achieve it:

bsize = ms.Length;
ms.Write(BitConverter.GetBytes(bsize), 0, intsize);
ms.Position = 0;
tcp.GetStream().Write(ms.GetBuffer(), 0, (int)bsize+4);


So, I thought: why can't you just write the length to the MemoryStream and add it before the actual data?

But, it doesn't work, and I am not sure if it's adding or overwriting data.  I suppose it's overwriting, which means it won't work.

From my testing, I think Write adds data to the end, which complicates things.
I was looking into the MemoryStream and I found this 


  Except for a MemoryStream constructed with a byte[] parameter, write operations at the end of a MemoryStream expand the MemoryStream.


on MemoryStream.Write Method

I would look around a little bit on the MSDN sites that I am going to list and see if you want to change around the code that you have so that you can maybe use the Byte[] Parameter.

MemoryStream Class

although it looks like most of those Constructors create non-resizable instances, whereas the a Memory Stream Created with out any Parameters ...


  Initializes a new instance of the MemoryStream class with an expandable capacity initialized to zero. 


so to me it looks like the BlockCopy or 2 streams methods are the only way to go.