Stream Class

Overview

  • A stream is an abstraction of a sequence of bytes, which helps isolating the programmer from the underlying implementation.

Good practice

  • Remember to call Close on a stream.
    • Calling Close on a Stream flushes any buffered data, essentially calling Flush for you.
    • Close releases operating system resources such as file handles, network connections, or memory used for any internal buffering.
    • Make use of the finally block in a try/catch/finally when working with a stream, demonstrated below.

Examples

Finally Block

StreamReader sr = new StreamReader("text.txt");
try
{
    Console.WriteLine(sr.ReadToEnd());
}
catch (Exception ex)
{
    // If there are any problems reading the file, display an error message
    Console.WriteLine("Error reading file: " + ex.Message);
}
finally
{
    // Close the StreamReader, whether or not an exception occurred
    sr.Close();
}