Stream Class
Part of my 2008 study notes for exam 70-536 (.NET Framework 2.0).
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();
}
You May Also Like
ArrayList Class
Resizeable, unordered, index-based collection. Suffers from boxing/unboxing when working with value types. Implements IEnumerator, allowing foreach…
BinaryReader Class and BinaryWriter Class
Used to read and write binary data from streams. Call the correct Read methods when using a BinaryReader.
BitArray Class
Contains an array of true/false values. Resizable through the Length property. Supports bitwise operations.



