Sending data through a TCP stream I've noticed that there are several ways of sending data through a TCP stream. I want to do it the fastest way in terms of latency.

One method I became aware of is with a binary writer:

using (MemoryStream ms = PrintWindow(process))
{
    writer.Write((int)ms.Length);
    writer.Write(ms.GetBuffer(), 0, (int)ms.Length);
}


And to receive it:

Image.FromStream(new MemoryStream(reader.ReadBytes(reader.ReadInt32())));


It writes the size for reference, then takes the data.

For the other method, which is a bit sensitive, it seems that it can easily fail if the image changes for some reason:

using (MemoryStream ms = PrintWindow(process))
{    
    tcp.GetStream().Write(ms.GetBuffer(), 0, tcp.SendBufferSize); 
}


And to receive it:

byte[] b = new byte[tt1.ReceiveBufferSize];
tt1.GetStream().Read(b, 0, tt1.ReceiveBufferSize);
Image.FromStream(new MemoryStream(b));


I've found this with trial and error.  But, as I've said, it's very sensitive and can cause an error if the image changes in a certain way.  I'm not absolutely sure why, though.

Which of these is the fastest?  In my view, writing with just the stream should be faster than with some special writer.

The error I get when using the second method seems to occur when the data is very low.  For example: a black or near-black picture. If anyone knows how to solve this, please let me know.

It seems that I need to have the TCP Send and Receive buffer at least as big as the largest file for it to work, so I've increased it by x128.  I'm not sure if that's a good idea or not, but from my understanding, the only thing it does is allocate more RAM.  Then again, I think it's probably because I set the byte size to the buffer size.
If you are looking for ways to optimize your application - you are clearly looking at the wrong place, at least in my opinion. BinaryWriter is a simple wrapper around actual stream. All it does is it converts simple types to byte arrays and writes those to stream. Ofc it is slower, as any other wrapper, but not that much slower. In real life this difference can be ignored.

If writing to NetworkStream is your main performance issue, then consider wrapping it with BufferedStream. 

If it isnt, and you are simply curious... then you can always use disassembler to see whats inside BinaryWriter.Write method for yourself.