Free mag vol1 | Page 829

CHAPTER 20  FILE I/O AND OBJECT SERIALIZATION static void Main(string[] args) { Console.WriteLine("***** Fun with StringWriter / StringReader *****\n"); // Create a StringWriter and emit character data to memory. using(StringWriter strWriter = new StringWriter()) { strWriter.WriteLine("Don't forget Mother's Day this year..."); // Get a copy of the contents (stored in a string) and dump // to console. Console.WriteLine("Contents of StringWriter:\n{0}", strWriter); } Console.ReadLine(); } StringWriter and StreamWriter both derive from the same base class (TextWriter), so the writing logic is more or less identical. However, given the nature of StringWriter, you should also be aware that this class allows you to use the following GetStringBuilder() method to extract a System.Text.StringBuilder object: using (StringWriter strWriter = new StringWriter()) { strWriter.WriteLine("Don't forget Mother's Day this year..."); Console.WriteLine("Contents of StringWriter:\n{0}", strWriter); } // Get the internal StringBuilder. StringBuilder sb = strWriter.GetStringBuilder(); sb.Insert(0, "Hey!! "); Console.WriteLine("-> {0}", sb.ToString()); sb.Remove(0, "Hey!! ".Length); Console.WriteLine("-> {0}", sb.ToString()); When you want to read from a stream of character data, you can use the corresponding StringReader type, which (as you would expect) functions identically to the related StreamReader class. In fact, the StringReader class does nothing more than override the inherited members to read from a block of character data, rather than from a file, as shown here: using (StringWriter strWriter = new StringWriter()) { strWriter.WriteLine("Don't forget Mother's Day this year..."); Console.WriteLine("Contents of StringWriter:\n{0}", strWriter); } // Read data from the StringWriter. using (StringReader strReader = new StringReader(strWriter.ToString())) { string input = null; while ((input = strReader.ReadLine()) != null) { Console.WriteLine(input); } } 775