Curriculum
In C#, the StreamReader class is used to read text from a file in a high-level, sequential manner. It provides methods for reading strings, characters, and lines of text from a file, as well as methods for checking the end of the stream and closing the stream.
Here is an example of using StreamReader to read text from a file:
using System.IO; class Program { static void Main() { string filePath = "example.txt"; using (StreamReader reader = new StreamReader(filePath)) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } } } }
In this example, we create a StreamReader object by specifying the file path. We then use a while loop to read lines of text from the file using the ReadLine method. The loop continues until the end of the file is reached, at which point ReadLine returns null.
Here is an example of using StreamReader to read all text from a file:
using System.IO; class Program { static void Main() { string filePath = "example.txt"; using (StreamReader reader = new StreamReader(filePath)) { string text = reader.ReadToEnd(); Console.WriteLine(text); } } }
In this example, we create a StreamReader object by specifying the file path. We then use the ReadToEnd method to read all text from the file and store it in a string. Finally, we write the string to the console.
Overall, StreamReader is a useful class for reading text from files in C#. It provides a high-level, convenient way to read text from files, but it does not provide the low-level control and efficiency of FileStream. It also requires careful attention to detail and proper error handling to ensure that files are read correctly.