A stream is an object that provides a low-level means to transfer data. They themselves do not act as data containers.
The data that we deal with is in form of byte array(
byte ). The functions for reading and writing are all byte orientated, e.g.
There are no functions for dealing with integers, strings etc. This makes the stream very general-purpose, but less simple to work with if, say, you just want to transfer text. Streams can be particularly very helpful when you are dealing with large amount of data.
We will need to use different type of Stream based where it needs to be written/read from (i.e. the backing store). For example, if the source is a file, we need to use
MemoryStream is used if the backing store is memory:
System.Net.Sockets.NetworkStream is used for network access.
All Streams are derived from the generic class
System.IO.Stream. Data cannot be directly read or written from streams. The .NET Framework provides helper classes such as
BinaryWriter that convert between native types and the low-level stream interface, and transfer the data to or from the stream for you.
Reading and writing to streams can be done via
StreamWriter. One should be careful when closing these. By default, closing will also close contained stream as well and make it unusable for further uses. This default behaviour can be change by using a constructor which has
bool leaveOpen parameter and setting its value as
StreamWriter, etc. implement the
IDisposable interface, we can call the
Dispose() method on objects of these classes.