📜  C#StreamReader(1)

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

C# StreamReader

In C#, StreamReader is used to read characters from a stream of data. It is part of the System.IO namespace and provides a simple way to read text from files, network streams, and other sources.

Creating a StreamReader Object

To create a StreamReader object, you need to give it a stream to read from. Here is an example of how to create a StreamReader object to read from a file:

StreamReader reader = new StreamReader("file.txt");

In this example, file.txt is the name of the file you want to read from. You can also create a StreamReader object to read from a network stream or other source.

Reading Text with a StreamReader Object

After you have created a StreamReader object, you can use its methods to read text from the stream. The Read method returns the next character in the stream as an integer. You can then cast it to a char to get the actual character.

int nextChar = reader.Read();
char nextCharAsChar = (char)nextChar;

Alternatively, you can use the ReadLine method to read an entire line of text from the stream.

string line = reader.ReadLine();
Closing a StreamReader Object

When you are finished reading from a stream, you should close the StreamReader object. This will release any resources that were used by the object.

reader.Close();

You can also use the using statement to ensure that the StreamReader object is closed automatically when it is no longer needed.

using (StreamReader reader = new StreamReader("file.txt")) 
{
    // Read from the stream here...
}
Conclusion

StreamReader is a useful class in C# for reading text from a stream. With its simple API, you can easily read from files, network streams, and other sources. Remember to always close your StreamReader objects when you are finished reading from them to release any resources that were used.