Free mag vol1 | Page 826

CHAPTER 20  FILE I/O AND OBJECT SERIALIZATION  Note The last two members of the TextWriter class probably look familiar to you. If you recall, the System.Console type has Write() and WriteLine() members that push textual data to the standard output device. In fact, the Console.In property wraps a TextWriter, and the Console.Out property wraps a TextReader. The derived StreamWriter class provides an appropriate implementation for the Write(), Close(), and Flush() methods, and it defines the additional AutoFlush property. When set to true, this property forces StreamWriter to flush all data every time you perform a write operation. Be aware that you can gain better performance by setting AutoFlush to false, provided you always call Close() when you finish writing with a StreamWriter. Writing to a Text File To see the StreamWriter type in action, create a new Console Application named StreamWriterReaderApp and import System.IO. The following Main() method creates a new file named reminders.txt using the File.CreateText() method. Using the obtained StreamWriter object, you can add some textual data to the new file. static void Main(string[] args) { Console.WriteLine("***** Fun with StreamWriter / StreamReader *****\n"); // Get a StreamWriter and write string data. using(StreamWriter writer = File.CreateText("reminders.txt")) { writer.WriteLine("Don't forget Mother's Day this year..."); writer.WriteLine("Don't forget Father's Day this year..."); writer.WriteLine("Don't forget these numbers:"); for(int i = 0; i < 10; i++) writer.Write(i + " "); } // Insert a new line. writer.Write(writer.NewLine); Console.WriteLine("Created file and wrote some thoughts..."); Console.ReadLine(); } After you run this program, you can examine the contents of this new file (see Figure 20-3). You will find this file under the bin\Debug folder of your current application because you did not specify an absolute path at the time you called CreateText(). 772