C# StringReader Class
Being a subclass of the TextReader class, the StringReader class facilitates constructors and methods to perform read operations and is thus used for reading data written by the StringWriter class, synchronously or asynchronously.
C# StringReader Signature:
- [SerializableAttribute]
- [ComVisibleAttribute(true)]
- public class StringReader : TextReader
C# StringReader Constructors:
Constructors | Uses |
StringReader(String) | To initialize a new instance of the StringReader class to read from the specified string. |
C# StringReader Methods:
Method | Uses |
Close() | To close the StringReader. |
Dispose() | To release all the resources used by the TextReader object. |
Equals(Object) | To check if the specified object is equal to the current object or not. |
Finalize() | To provide an access to an object to try to free resources and perform other cleanup operations. |
GetHashCode() | To act as the default hash function. |
GetType() | To return the type of the current instance. |
Peek() | To get the next available character without consuming. |
Read() | For reading the next character from the input string. |
ReadLine() | For reading a line of characters from the current string. |
ReadLineAsync() | For reading a line of characters asynchronously from the current string. |
ReadToEnd() | For reading all the characters from the current position to the end of the string. |
ReadToEndAsync() | For reading all the characters from the current position to the end of the string asynchronously. |
ToString() | To get a string that represents the current object. |
Example:
using System; using System.IO; namespace Example { class content { static void Main(string[] args) { StringWriter writer = new StringWriter(); writer.WriteLine("Hello World!!"); writer.Close(); StringReader rdr = new StringReader(writer.ToString()); while (rdr.Peek() > -1) { Console.WriteLine(rdr.ReadLine()); } } } } |
Output:
Explanation:
In the above example, we are using the StringWriter class for writing the string information. For reading the string written by the StringWriter class, the StringReader class is used. The written string is thus displayed on the console screen.