StreamReader, ReadToEnd. Sometimes we want to read in a file line-by-line, but other times we just want the entire file at once. The ReadToEnd method on StreamReader is helpful here.
With this method, we consume the entire file into a string in one line. This is similar in operation to File.ReadAllText. But StreamReader requires some surrounding code.
An example. Here is the ReadToEnd method. We can call it inside a using-statement for best effect. Please change the file path before you run this program on your system.
using System;
using System.IO;
class Program
{
static void Main()
{
using (StreamReader reader = new StreamReader(@"C:\programs\file.txt"))
{
// Read entire text file with ReadToEnd.
string contents = reader.ReadToEnd();
Console.WriteLine(contents);
}
}
}Thank you
Friend
A review. Which methods are best? If you already have a StreamReader, then using ReadToEnd is probably the best solution to read an entire text file into a string.
However In other programs, where no StreamReader object exists, File.ReadAllText is probably a clearer method to use.
ReadToEndAsync. With ReadToEndAsync on StreamReader, we can achieve a significant performance boost. But this only helps when a lot of CPU usage is present during processing.
A summary. ReadToEnd is important enough that it deserves special attention. I have used it recently in a program—sometimes it leads to clearer code than ReadLine and while-loops would.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.