
StreamReader Class and StreamWriter Class
Part of my 2008 study notes for exam 70-536 (.NET Framework 2.0).
Overview
- Provides extra helper methods intended to read a stream as a string.
- Calling Close() on a StreamReader will close the underlying Stream as well.
Good practice
- Remember to call Close on a stream.
- Use
usingstatements when you want the stream to be closed automatically at the end.
Examples
Read a File
// FileStream is simply a stream around a file, overriding Stream methods
FileStream a = new FileStream(@"C:\Public\Test.txt", FileMode.Open);
while (a.Position != a.Length)
{
Console.Write((char)a.ReadByte());
}
a.Seek(0, SeekOrigin.Begin);
StreamReader b = new StreamReader(a);
Console.WriteLine(b.ReadToEnd());
b.Close();
Writing a File
// FileStream is simply a stream around a file, overriding Stream methods
FileStream a = new FileStream(@"C:\Public\Test.txt", FileMode.Create);
using (StreamWriter writer = new StreamWriter(a))
{
writer.AutoFlush = true;
writer.WriteLine("Hello World");
}
// The FileStream has been closed because of the using statement
a = new FileStream(@"C:\Public\Test.txt", FileMode.Open);
StreamReader b = new StreamReader(a);
Console.WriteLine(b.ReadToEnd());
b.Close();
// Simple version if you only need to read the entire file
Console.WriteLine(File.ReadAllText(@"C:\Public\Test.txt"));
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.



