StringWriter and StringReader

The StringWriter class in .NET Framework serves as a TextWriter implementation that enables writing information to a string. It internally utilizes the StringBuilder class to store the written information. The StringBuilder class, on the other hand, represents a mutable string of characters and cannot be inherited.

StringWriter class

By using the StringWriter class, developers can easily write data to a string in a convenient and efficient manner. The written information is automatically stored in the underlying StringBuilder object, allowing for easy retrieval and manipulation.

The WriteLine(String) method, available in StringWriter, is used to write a string followed by a line terminator to the text stream. This method appends the specified string to the internal StringBuilder object and appends a line terminator character sequence to mark the end of the line.

Dim stringWriter As New StringWriter() stringWriter.WriteLine("https://net-informations.com/vb/default.htm")

StringReader class

On the other hand, the StringReader class implements a TextReader that allows reading from a string. It provides functionality to read character data sequentially from the underlying string source.

Dim message As String Dim stringReader As New StringReader(String)

The ReadLine method in StringReader is used to read a line of text from the underlying string. It reads characters until it encounters a line terminator sequence or reaches the end of the string.

The following program shows how to use StringWriter and StringReader Classes in VB.NET.

Full Source VB.NET
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim stringWriter As New StringWriter() stringWriter.WriteLine("net-informations.com") stringWriter.WriteLine("https://net-informations.com/vb/default.htm") stringWriter.WriteLine("csharp.net-informations.com") MsgBox(stringWriter.ToString) Dim singleLine As String Dim message As String Dim stringReader As New StringReader(stringWriter.ToString) While True singleLine = stringReader.ReadLine If singleLine Is Nothing Then Exit While Else message = message & singleLine & Environment.NewLine End If End While MsgBox(message) End Sub End Class

Conclusion

Using the StringWriter and StringReader classes, developers can efficiently write and read string data. This is particularly useful when working with string-based operations and when there is a need to manipulate or process string content in memory without directly interacting with external files or streams.