C# using streams

Martijn picture Martijn · Sep 10, 2009 · Viewed 111.2k times · Source

Streams are kind of mysterious to me. I don't know when to use which stream and how to use them. Can someone explain to me how streams are used?

If I understand correctly, there are three stream types:

  • stream
  • read stream
  • write stream

Is this correct? And, for example, what is the difference between a Memorystream and a FileStream?

Answer

Arsen Mkrtchyan picture Arsen Mkrtchyan · Sep 10, 2009

A stream is an object used to transfer data. There is a generic stream class System.IO.Stream, from which all other stream classes in .NET are derived. The Stream class deals with bytes.

The concrete stream classes are used to deal with other types of data than bytes. For example:

  • The FileStream class is used when the outside source is a file
  • MemoryStream is used to store data in memory
  • System.Net.Sockets.NetworkStream handles network data

Reader/writer streams such as StreamReader and StreamWriter are not streams - they are not derived from System.IO.Stream, they are designed to help to write and read data from and to stream!