StringWriter StringReader

The string type in C# serves as a representation of a sequence of Unicode characters, and it can contain zero or more characters. It's worth noting that the lowercase "string" is an alias for the "String" class within the .NET Framework.

The StringWriter class is designed to implement a TextWriter, which facilitates writing information to a string. This class stores the information in an underlying StringBuilder, which provides efficient string manipulation capabilities.

StringWriter stringWriter = new StringWriter(); stringWriter.WriteLine("csharp.net-informations.com");

The WriteLine(String) method, belonging to the StringWriter (and also available in other TextWriter implementations), writes a specified string to the text stream and appends a line terminator. This method is useful for formatting output when writing to a string.

StringReader.ReadLine method

On the other hand, the StringReader class implements a TextReader specifically designed for reading from a string. It allows you to read characters and strings from the underlying string in a sequential manner.

stringReader.ReadLine();

The StringReader.ReadLine method, present in the StringReader class, reads a single line from the underlying string, up to the point where it encounters a line terminator. This method is commonly used to read and process text line by line when working with string input.

The following program shows how to use StringWriter and StringReader Classes in C#.

Full Source C#
using System; using System.IO; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { StringWriter stringWriter = new StringWriter(); stringWriter.WriteLine("net-informations.com"); stringWriter.WriteLine("https://net-informations.com/vb/default.htm"); stringWriter.WriteLine("csharp.net-informations.com"); MessageBox.Show (stringWriter.ToString()); string singleLine = null; string message = null; StringReader stringReader = new StringReader(stringWriter.ToString()); while (true) { singleLine = stringReader.ReadLine(); if (singleLine == null) { break; } else { message = message + singleLine + Environment.NewLine; } } MessageBox.Show (message); } } }

Conclusion

These classes and methods provide convenient functionalities for working with strings, enabling efficient reading and writing operations when interacting with text-based data.