StringWriter vs StringReader in C#?

CsharpProgrammingServer Side Programming

StringReader and StringWriter derive from TextReader and TextWriter

StringWriter is used for writing into a string buffer. It implements a TextWriter for writing information to a string.

For StringWriter −

Example

StringWriter sWriter = new StringWriter();
while(true) {
   myChar = strReader.Read();
   if(myChar == -1) break;

   convertedChar = Convert.ToChar(myChar);
   if(convertedChar == '.') {
      strWriter.Write(".

");       sReader.Read();       sReader.Read();    }else {       sWriter.Write(convertedChar);    } } }

StringReader to read a string −

Example

StringBuilder sbuilder = new StringBuilder();

// append
sbuilder.AppendLine("Line one characters");
sbuilder.AppendLine("Line two characters");
sbuilder.AppendLine("Line three characters");

// read string
using (StringReader sReader = new StringReader(sbuilder.ToString())) {
   string readString = await sReader.ReadToEndAsync();
   Console.WriteLine(readString);
}
raja
Updated on 21-Jun-2020 16:44:42

Advertisements