Overview
- A stream is an abstraction of a sequence of bytes, which helps isolate 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

Exam 70-536 Study Notes
My study notes for Microsoft exam 70-536: .NET types, collections, generics, I/O, serialization and more, with C# examples.

Starting Exam 70-536 Study
After a burnout, I'm putting my own project on hold to study for Microsoft exam 70-536.

Design Patterns - Proxy Pattern
The Proxy Pattern, and the last article in the design patterns series, now that I've finished reading Head First Design Patterns.




