StringReader/StringWriter
GetBytes and GetChars methods maintain no state between conversions.
The core GetBytes and GetChars methods require you to provide the destination buffer and ensure that the
buffer is large enough to hold the entire result of the conversion. An application can use one of the following
methods to calculate the required size of the destination buffer.
The GetByteCount and GetCharCount methods can be used to compute the exact size of the result of a
particular conversion, and an appropriately sized buffer for that conversion can then be allocated.
The GetMaxByteCount and GetMaxCharCount methods can be used to compute the maximum possible
size of a conversion of a given number of bytes or characters, and a buffer of that size can then be reused for
multiple conversions.
The GetMaxByteCount method generally uses less memory, whereas the second method
GetMaxCharCount generally executes faster. See the .NET Framework SDK documentation for the various
encoding and decoding methods.
StringReader/StringWriter
Besides the standard methods of the StringBuilder class, which make it useful on its own, the framework
bridges StringBuilder to both the StringWriter and StringReader classes. This cooperation between the
"builder" classes and the "transport" classes lets you stream characters into and out of StringBuilder objects
as a type of staging area where Strings get to go to be manipulated. You can think of these classes as the
instruments you can use to write and read characters to the StringBuilder object.
Despite being the StringBuilder's apprentices, these classes are located in the System.IO namespace (while
StringBuilder lives in System.Text), which has a lot to do with the fact that StringWriter derives from
TextWriter (discussed in this section). Table 15−27 presents the important members of the StringReader
class.
The syntax for creating a StringReader class is as follows:
Dim s as new StringReader("C:\MyFile.txt")
Table 15−28 lists the members of the StringWriter class.
Note If these methods look familiar, they should. The Console class uses synchronized (thread−safe)
instances of TextWriter and TextReader to write to and read from the console. Later, we take a look at
the support for streaming and how all these classes connect.
Table 15−27: The Members of the StringReader Class
Member Purpose
Close Closes the StringReader
Peek Returns the next available character but does not consume it
Read Reads the next character or next set of characters from the input string
ReadBlock Reads a maximum of counted characters from the current stream and writes the
data to the buffer, beginning at a specified location
546