NetworkStream.Write vs. Socket.Send

Brian Tacker picture Brian Tacker · Jul 2, 2011 · Viewed 14.7k times · Source

I have a c# application that I use a custom FTP library for. Right now Im using Socket.Send to send the data but I was wondering if it would be better to initiate a NetworkStream with the socket and use NetworkStream.Write instead.

Are there any advantages to using one over the other?

Answer

Rick Sladkey picture Rick Sladkey · Jul 2, 2011

The advantage of a NetworkStream derives primarily from the fact that it is a Stream. The disadvantage of a Socket is that common code that reads and writes from abstract I/O sources like a Stream cannot handle a Socket.

The main use case for a NetworkStream is that you have some code elsewhere that reads or writes from a Stream, and you wish you could use it with a Socket. You would know if were in this situation and then NetworkStream would be a big help!

Say for example you had a communications library and you supported serializing messages from files, named pipes and TCP/IP. The ideal choice for the I/O class would be Stream. Then your serialization methods could accept a FileStream, a PipeStream, or a NetworkStream. It would even accept a MemoryStream. This is the benefit of abstraction because after we've created the stream, a method can interact with it without knowing what kind of stream it is.

In this sense, a NetworkStream uses the adapter design pattern. It adapts the Socket API to the Stream API so that clients that are expecting a Stream can use it.

So finally, the question, if NetworkStream is a Stream adapter for a Socket, which one should we use? Well, if you need a Stream, then NetworkStream is your only choice. If you don't need a Stream, then you can use whichever API you are most comfortable with. If you are already using Socket successfully, there is no pressing reason to switch to NetworkStream.