To expand a little on other answers here, and help explain a lot of the example code you'll see dotted about, most of the time you don't read and write to a stream directly. Streams are a low-level means to transfer data.
You'll notice that the functions for reading and writing are all byte orientated, e.g. WriteByte(). 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.
However, .NET provides classes that convert between native types and the low-level stream interface, and transfers the data to or from the stream for you. Some notable such classes are:
StreamWriter // Badly named. Should be TextWriter.
StreamReader // Badly named. Should be TextReader.
BinaryWriter
BinaryReader
To use these, first you acquire your stream, then you create one of the above classes and associate it with the stream. E.g.
MemoryStream memoryStream = new MemoryStream();
StreamWriter myStreamWriter = new StreamWriter(memoryStream);
StreamReader and StreamWriter convert between native types and their string representations then transfer the strings to and from the stream as bytes. So
myStreamWriter.Write(123);
will write "123" (three characters '1', '2' then '3') to the stream. If you're dealing with text files (e.g. html), StreamReader and StreamWriter are the classes you would use.
Whereas
myBinaryWriter.Write(123);
will write four bytes representing the 32-bit integer value 123 (0x7B, 0x00, 0x00, 0x00). If you're dealing with binary files or network protocols BinaryReader and BinaryWriter are what you might use. (If you're exchanging data with networks or other systems, you need to be mindful of endianness, but that's another post.)
Stream
) which exposes some helpful methods such as reading, writing and changing position. Now you can create classes based on their backing store (FileStream, MemoryStream) which inherit fromStream
and build upon that functionality based on the particular backing store. – Palpitation