CHAPTER 20 FILE I/O AND OBJECT SERIALIZATION
while ((input = sr.ReadLine()) != null)
{
Console.WriteLine (input);
}
}
}
Console.ReadLine();
After you run the program, you will see the character data in reminders.txt displayed to the console.
Directly Creating StreamWriter/StreamReader Types
One of the confusing aspects of working with the types within System.IO is that you can often achieve an
identical result using different approaches. For example, you have already seen that you can use the
CreateText() method to obtain a StreamWriter with the File or FileInfo type. It so happens that you
can work with StreamWriters and StreamReaders another way: by creating them directly. For example,
you could retrofit the current application as follows:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with StreamWriter / StreamReader *****\n");
// Get a StreamWriter and write string data.
using(StreamWriter writer = new StreamWriter("reminders.txt"))
{
...
}
}
// Now read data from file.
using(StreamReader sr = new StreamReader("reminders.txt"))
{
...
}
Although it can be a bit confusing to see so many seemingly identical approaches to file I/O, keep in
mind that the end result is greater flexibility. In any case, you are now ready to examine the role of the
StringWriter and StringReader classes, given that you have seen how to move character data to and
from a given file using the StreamWriter and StreamReader types.
Source Code You can find the StreamWriterReaderApp project under the Chapter 20 subdirectory.
Working with StringWriters and StringReaders
You can use the StringWriter and StringReader types to treat textual information as a stream of inmemory characters. This can prove helpful when you would like to append character-based information
to an underlying buffer. The following Console Application (named StringReaderWriterApp) illustrates
this by writing a block of string data to a StringWriter object, rather than to a file on the local hard drive:
774