The StringReader and StringWriter classes, also derived from TextReader and TextWriter, are mainly used to manipulate strings rather than files. The StringReader class is built from a string and provides methods Read and ReadLine to read parts of that string. The StringWriter class is used to write to a StringBuilder class (from the System.Text namespace). Since strings in C# are immutable, the StringBuilder class is used to build a string efficiently. StringWriter provides methods like Write and WriteLine to write to the StringBuilder object. Use these streams if you are dealing with many string manipulations (e.g., a text-to-HTML parser). The StringRW class in Listing 6.11 is similar to the StreamRW class shown in Listing 6.10, except that it uses the StringReader and StringWriter classes.
Listing 6.11: StringReader and StringWriter Example
using System;
using System.IO;
using System.Text;
public class StringRW
{
StringBuilder sb = new StringBuilder();
public StringRW()
{
//Call the Writer Method
Writer();
//Call the Reader Method
Reader();
}
public static void Main()
{
StringRW srw = new StringRW();
}
//Writer Method
private void Writer()
{
StringWriter sw = new StringWriter(sb);
Console.WriteLine("Welcome to the Profile Program");
Console.Write("Name :");
//Get the name from the console
string name = Console.ReadLine();
//Write to StringBuilder
sw.WriteLine("Name :" + name);
Console.Write("Country :");
string country = Console.ReadLine();
//Write to StringBuilder
sw.WriteLine("Country :" + country);
Console.Write("Age :");
string age = Console.ReadLine();
//Write to StringBuilder
sw.WriteLine("Age :" + age);
Console.WriteLine("Thank You");
Console.WriteLine("Information Saved!");
Console.WriteLine();
//Close the stream
sw.Flush();
sw.Close();
Console.ReadLine();
}
private void Reader()
{
StringReader sr = new StringReader(sb.ToString());
Console.WriteLine("Reading Profile");
//Peek to see if the next character exists
while (sr.Peek() > -1)
{
//Read a line from the string and display it on the
//console
Console.WriteLine(sr.ReadLine());
}
Console.WriteLine("Data Read Complete!");
//Close the string
sr.Close();
}
}
Output of listing 6.11
Instead of using a file as a data source (as in the StreamRW class in Listing 6.10), this example uses a StringBuilder object to store the input from the user in the Writer method using the StringWriter class. Later, in the Reader method, the example uses the StringReader class to read from the string, which was built in the Writer method.
Primitive Type Stream
Primitive type streams serialize the primitive data types into their native formats. These streams are used when you want to store and retrieve data directly in the form of primitive data types like int, double, char, and byte.