This post will discuss how to read the entire text from a file into a string in C#.

1. Using File.ReadAllText() method (System.IO)

The recommended solution to read all the text in the file into a string is to use the File.ReadAllText() method. The following code example demonstrates its usage to display the contents of a file.

Download Code

 
The File.ReadAllText() method automatically tries to detect the encoding of a file. It has an overloaded version that takes the encoding of the file. It throws an IOException if an I/O error occurs while opening the specified file and FileNotFoundException if the source file is not found.

2. Using StreamReader.ReadToEnd() method (System.IO)

Another solution to read the whole file and copy the file contents to a string is using the StreamReader.ReadToEnd() method.

The following code gets a StreamReader instance using the File.OpenText method and then uses the ReadToEnd() method to read all the way to the end of a file in a single operation. Since the StreamReader object is declared and instantiated in a using statement, the Dispose() method is automatically invoked to flush and closes the stream.

Download Code

 
The File.OpenText() method opens an existing UTF-8 encoded text file for reading. To open a file with some other character encoding, use the StreamReader class constructor, which optionally takes a specific character encoding.

The following example gets a new StreamReader in ASCII format from a file with byte order mark detection as true:

Download  Run Code

That’s all about reading an entire file to a string with C#.