📜  C#TextReader(1)

📅  最后修改于: 2023-12-03 15:14:27.573000             🧑  作者: Mango

C# TextReader

The TextReader class in C# is used for reading characters and strings from a text-based stream. It is an abstract base class, and cannot be directly instantiated. Instead, it is implemented by other classes such as StreamReader and StringReader.

Example Usage
string input = "This is a test string.";
StringReader reader = new StringReader(input);
int character = reader.Read();
while (character != -1)
{
    Console.Write((char)character);
    character = reader.Read();
}

In this example, we create a StringReader object with a test string. We then read characters from the stream until we reach the end of the stream (indicated by a -1 return value from Read()). We cast each character to a char and print it to the console.

Common Methods
  • Read() - Reads the next character from the input stream and advances the character position. Returns -1 if the end of the stream has been reached.
  • ReadBlock(char[] buffer, int index, int count) - Reads a specified maximum number of characters into a buffer.
  • ReadLine() - Reads a line of characters from the input stream.
  • ReadToEnd() - Reads all characters from the current position to the end of the input stream.
Conclusion

The TextReader class provides a simple and efficient way to read characters from a text-based input stream. It is used extensively in C# programming for reading input from files, network streams, and other sources.