This post will discuss how to how to read from a file in C#.

1. Using File Class

A simple solution to read all the text in the file in one go is to use the ReadAllText() method. The following example demonstrates its usage:

Download Code

 
The File.ReadAllLines() method read all the lines of the specified file into a string array. It can be used as follows:

Download Code

 
You should not use the above methods with large files. The ReadLines() method is preferred over the ReadAllLines() method as ReadLines returns an Enumerable, and you can enumerate before the whole collection is returned.

Download Code

2. Using FileStream Class

For large files, you can use the FileStream.Read() method to read the whole file in chunks. Here’s an example of how you could achieve that.

Download Code

3. Using StreamReader Class

Another option is to use the StreamReader.ReadLine() method. You can use it to read lines from a file until the end of the file is reached.

Download Code

 
For small files, you can use the StreamReader.ReadToEnd() method, which reads the whole file in a single operation.

Download Code

That’s all about reading from a file in C#.